Dynamic import compiles to `require()`, which throw errors when importing ES modules
aquapi opened this issue ยท 5 comments
Bug Report
The dynamic import feature supports importing ES modules into CommonJS modules. npx tsc
compiles dynamic import to __importStar(require())
which cannot import ES modules
๐ป Code
import("file.mjs")
๐ Actual behavior
__importStar(require("file.mjs"))
๐ Expected behavior
import("file.mjs")
To get that behavior, set module
to esnext
This issue has been marked as 'Question' and has seen no recent activity. It has been automatically closed for house-keeping purposes. If you're still waiting on a response, questions are usually better suited to stackoverflow or the TypeScript Discord community.
Hello here is the use case.
we want TypeScript emit commonjs modules in node.js, and node tell us we can use
dynamic import in commonjs module to load an esm module. https://nodejs.org/dist/latest-v16.x/docs/api/esm.html#import-expressions
tsconfig.compilerOptions.module can not be changed, since esm & commonjs have many differneces, migrate a whole project would be a big effort.
To get that behavior, set moduleResolution
to node16
while leaving module
to commonjs
.
This will convert all imports to requires, except dynamic imports (await import()
)