最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Typescript es6 modules re-export mutable variable binding - Stack Overflow

programmeradmin2浏览0评论

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

{
  "pilerOptions": {
    "target": "es5",
    "module": "monjs",
    "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 pile 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?

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

{
  "pilerOptions": {
    "target": "es5",
    "module": "monjs",
    "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 pile 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?

Share Improve this question edited Jan 5, 2016 at 13:11 Venkat.R 7,7765 gold badges44 silver badges68 bronze badges asked Jan 5, 2016 at 12:00 Jonas KelloJonas Kello 1,4323 gold badges16 silver badges29 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

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
发布评论

评论列表(0)

  1. 暂无评论