I am trying to re-export a variable using es6 module syntax, then change it and see the change reflected in the final import. But it is not working as expected. See the example below:
a.ts
export var a = 1;
export function changeA() { a = 2; }
b.ts
export * from './a';
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 run:
$ node out/c.js
1
1
I expect the final console.log to print 2 in order to reflect the update but it does not. However, if I compile the same example with babel it works. Does re-exporting mutable variable bindings not work with typescript at all or am I just doing something wrong?
It is because b.ts
:
export * from './a';
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.
You can work it around this way:
a.ts:
export var a = 1;
export var deeper = {
a: 1
};
export function changeA() {
a = 2;
deeper.a = 2;
}
b.ts:
export * from './a';
c.ts:
import { a, deeper, changeA } from './b';
console.log(a); // 1
changeA();
console.log(a); // Expected 2 but get 1
console.log(deeper.a); // prints 2 as expected
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With