Skip to content

ES6 module variables are copied when re-exported #6366

Closed
@jonaskello

Description

@jonaskello

Given this example:

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 runing c.js:

$ node out/c.js
1
1

This happens because in b.ts this:

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.

If I run the same example through babel it works because it generates getters that references the original variable. This was also proposed here.

I propose that if the target is set to es5 then the generated code for commonjs modules uses getters instead to make sure that re-exported variables are referenced instead of copied.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Breaking ChangeWould introduce errors in existing codeES6Relates to the ES6 SpecIn DiscussionNot yet reached consensusSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions