I'm exploring the distinction between import
and require
in relation to exporting and importing mutable values.
Picture a file a.ts:
export let a = 1;
export function f() {
a = 2;
}
Next, we have three versions of a main file, index1.ts:
import { a, f } from "./a";
console.log(a); // 1
f();
console.log(a); // 2
index2.ts:
const { a, f } = require("./a");
console.log(a); // 1
f();
console.log(a); // 1
index3.ts:
const _ = require("./a");
console.log(_.a); // 1
_.f();
console.log(_.a); // 2
- It was anticipated that index1.ts would yield the same result as index2.ts, however it does not. The
import
eda
always points back to the actuala
variable from a.ts. What assurances exist that this behavior will persist? Is this behavior mandated by the specifications? - index3.ts functions because the properties of the object returned by
require
are getters. Yet, can we always count on this being the case? Is it reliable for the construction of a library, for instance?