简体   繁体   English

TypeScript ES6模块重新导出可变变量绑定

[英]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. 我正在尝试使用es6模块语法重新导出变量,然后对其进行更改并在最终导入中看到更改。 But it is not working as expected. 但是它没有按预期工作。 See the example below: 请参阅以下示例:

a.ts a.ts

export var a = 1;
export function changeA() { a = 2; }

b.ts b.ts

export * from './a';

c.ts c.ts

import { a, changeA } from './b';
console.log(a); // 1
changeA();
console.log(a); // Expected 2 but get 1

tsconfig.json 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. 我希望最终的console.log打印2以反映更新,但事实并非如此。 However, if I compile the same example with babel it works. 但是,如果我使用babel编译相同的示例,则它可以工作。 Does re-exporting mutable variable bindings not work with typescript at all or am I just doing something wrong? 重新导出可变变量绑定是否完全不适用于Typescript,还是我做错了什么?

It is because b.ts : 这是因为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. 并且变量a的值被复制而不被引用。

You can work it around this way: 您可以通过以下方式解决它:

a.ts : a.ts

export var a = 1;
export var deeper = {
    a: 1
};
export function changeA() {
    a = 2;
    deeper.a = 2;
}

b.ts : b.ts

export * from './a';

c.ts : 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM