Description
TypeScript Version: 3.9.2 & 4.0.0-dev.20200512
Search Terms: __setModuleDefault, __importStar, redefine, ts-lib
Code
Check out the full example at https://github.com/marcelltoth/typescript-bug
File dangerous-module.js
(commonjs module)
const a = {
someConstant: 2
};
module.exports = a;
// Allow use of default import syntax in TypeScript
module.exports.default = a;
This is a pattern seen in real world, when the authors of CJS modules are trying to be nice with us TypeScript users. This way the module is nicely consumable from TS without esModuleInterop. The pattern is used by - for example - axios
I have esModuleInterop and therefore allowSyntheticDefaultImports turned on. Then in another file:
File index.ts
import m, {someConstant} from './dangerous-module.js';
console.log(m);
console.log(someConstant);
I build it via tsc
, then run node dist/index.js
on the output.
Expected behavior:
The code logs to the console.
Actual behavior:
It throws on the import line like so:
/home/marcelltoth/source/typescript-bug/dist/index.js:10
Object.defineProperty(o, "default", { enumerable: true, value: v });
^TypeError: Cannot redefine property: default
at Function.defineProperty ()
at /home/marcelltoth/source/typescript-bug/dist/index.js:10:12
at __importStar (/home/marcelltoth/source/typescript-bug/dist/index.js:18:5)
at Object. (/home/marcelltoth/source/typescript-bug/dist/index.js:22:29)
at Module._compile (internal/modules/cjs/loader.js:1158:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
Playground Link: https://github.com/marcelltoth/typescript-bug
Related Issues: #37113