Open m-ronchi opened 7 months ago
I wanted to create a new issue targeting the same problem but then I found this one so I am commenting here. See this stackblitz.
// main.cts
(async () => {
const dep = await import('./dep.mjs');
console.log(dep);
})()
// dep.mts
export const dep = 'dependency';
I expected ts-node main.cts
and tsc && node dist/main.cjs
to behave the same but I get this error
Cannot find module '[..]/dep.mjs' imported from [..]/main.cts
~What do I need to do to make this run with ts-node?~
Edit: ts-node-esm main.cts
works for me.
It appears this broke in Node 18.19 and versions released since have the issue.
There have been multiple issues tracking facets of it, in multiple repositories (node, typescript, ts-node, esbuild, tsx among others), over the last few months, but no resolution. In #2094 the common strategy is to work around the issue - either downgrade Node to 18.18, or use whatever alternative works in your scenario, for example tsx
(in which the same issue is half-fixed). None of those workarounds represent an actual fix.
The scenario is very simple: it happens in mixed CJS/ESM repositories, using TS in development with tooling that isn't always new, and inevitably some dependencies that don't support a global switch to modules in package.json. Node and some tooling (tsx) defaults to CJS in the absence of type=module
in package.json, and so import
-s are now broken, especially in an .mjs file importing .ts, e.g. import { named } from './tsfile'
(treated as CJS). The CJS-compatible import('./file').then(...)
pattern works in the forced CJS context. Or you could rename your .ts
file to .mts
and hope that the ESM system wakes up.
I'd love if ts-node
had updates about this, but I'm already having to test with alternatives. 🤷
Search Terms
ESM CJS mixed project SyntaxError: Named export not found. The requested module is a CommonJS module, which may not support all module.exports as named exports.
Expected Behavior
ts-node works and prints
BAR
Actual Behavior
Steps to reproduce the problem
run this: ts-node-bug.zip
Minimal reproduction
lib.ts (inferred as CommonJS module)
test.mts (ESM)
Specifications
ts-node v10.9.2 node v20.11.1 compiler v5.4.2
tsconfig.json, if you're using one:
{ "name": "ts-node-bug", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@types/node": "^20.11.25", "ts-node": "^10.9.2" } }