Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript es6 modules re-export mutable variable binding

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?

like image 252
Jonas Kello Avatar asked Jan 05 '16 12:01

Jonas Kello


1 Answers

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
like image 78
Martin Vseticka Avatar answered Oct 10 '22 06:10

Martin Vseticka