Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Runtime error with *esModuleInterop* when CJS module has an export named "default" #38540

Copy link
Copy link
@marcelltoth

Description

@marcelltoth
Issue body actions

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

Reactions are currently unavailable

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptA bug in TypeScriptFix AvailableA PR has been opened for this issueA PR has been opened for this issue

Type

No type
No fields configured for issues without a type.

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions

    Morty Proxy This is a proxified and sanitized view of the page, visit original site.