Given this example:
a.ts
export var a = 1;
export function changeA() { a = 2; }
b.ts
c.ts
import { a, changeA } from './b';
console.log(a); // 1
changeA();
console.log(a); // Expected 2 but get 1
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"outDir": "out"
}
}
Result of runing c.js:
This happens because in b.ts this:
transpiles to
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
__export(require('./a'));
and the value of variable a is copied and not referenced.
If I run the same example through babel it works because it generates getters that references the original variable. This was also proposed here.
I propose that if the target is set to es5 then the generated code for commonjs modules uses getters instead to make sure that re-exported variables are referenced instead of copied.
Given this example:
a.ts
b.ts
c.ts
tsconfig.json
{ "compilerOptions": { "target": "es5", "module": "commonjs", "outDir": "out" } }Result of runing c.js:
This happens because in b.ts this:
transpiles to
and the value of variable a is copied and not referenced.
If I run the same example through babel it works because it generates getters that references the original variable. This was also proposed here.
I propose that if the target is set to es5 then the generated code for commonjs modules uses getters instead to make sure that re-exported variables are referenced instead of copied.