Typescript es6 modules re-export variable binding variable

I am trying to re-export a variable using es6 module syntax and then change it and see the change reflected in the final import. But it does not work 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" } } 

Execution Result:

 $ node out/c.js 1 1 

I expect the final console.log to print 2 to reflect the update, but that is not the case. However, if I compile the same example with babel, it works. Does re-branding of changed variable bindings not working with typescript at all or am I just doing something wrong?

+6
source share
1 answer

This is because b.ts :

 export * from './a'; 

translates to

 function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } __export(require('./a')); 

and the value of the variable a copied and not referenced.

You can work like this:

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 
+4
source

All Articles