microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
98.27k stars 12.21k forks source link

Default import from an ESM package into a CommonJS project with esModuleInterop is faulty #58341

Closed JonasDoe closed 2 weeks ago

JonasDoe commented 2 weeks ago

🔎 Search Terms

"cjs esm esModuleInterop default", "common esm esModuleInterop default"

🕗 Version & Regression Information

⏯ Playground Link

https://github.com/JonasDoe/typescript-esm-issue

💻 Code

With esModuleInterop=true:

import { default as Provider } from 'oidc-provider'; // this is an ESM project with export default class Provider
console.log('Created new Provider:', new Provider('http://example.tld'))

The transpiled code will be:

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const oidc_provider_1 = __importDefault(require("oidc-provider"));
console.log('Created new Provider:', new oidc_provider_1.default('http://example.tld'));

🙁 Actual behavior

🙂 Expected behavior

Additional information about the issue

The original suggestion that this is a bug in TypeScript came from here: https://github.com/panva/node-oidc-provider/discussions/1249#discussioncomment-9241520, and by a person with greater knowledge about Node and TypeScript. So I'm sorry if I left something unclear.

RyanCavanaugh commented 2 weeks ago

esModuleInterop depends on the __esModule property in order to work, but Node's --experimental-require-module doesn't generate that. See https://github.com/nodejs/node/issues/52697

RyanCavanaugh commented 2 weeks ago

Also https://github.com/nodejs/node/pull/52166

Once that experimental feature lands (unexperimentally) in Node, you'll need to a) update to a version of TypeScript, which will eventually exist, that supports it and b) set module: nodenext in tsconfig

JonasDoe commented 2 weeks ago

I see! Thank you for the reponse!