tsx: Cannot import named export from a typescript file in a workspace package if entry is using es modules and other package is not.
Cannot import named export from a typescript file in a workspace package if entry is using es modules and other package is not.
tsx will throw
SyntaxError: The requested module 'ts-package/src/file' does not provide an export named 'x'
I know this could be considered a node limitation but maybe we can compile typescript files to esm if entry is esm (even if workspace package does not have "type": "module"
Repro: https://github.com/remorses/tsx-repros
pnpm i
pnpm run import-ts-file
About this issue
- Original URL
- State: open
- Created 2 years ago
- Reactions: 16
- Comments: 16 (7 by maintainers)
Commits related to this issue
- test: failing test for #38 — committed to privatenumber/tsx by privatenumber 2 years ago
- `tsx` -> `ts-node` (Due to https://github.com/privatenumber/tsx/issues/38) — committed to mint-cash/burndrop-contracts by junhoyeo 4 months ago
- refactor: convert js files to ts Workaround for https://github.com/privatenumber/tsx/issues/38 But also, it's time for those to be TypeScript Note, I added `// @ts-nocheck` to the top of the files to... — committed to specify/specify7 by maxpatiiuk 4 months ago
Hi @privatenumber, I’ve just bumped into this issue trying to migrate a CJS project to ESM adding
"type": "module"to itspackage.json. The same thing - either I can’t load non-esm packages from the monorepo, or (if I add"type": "module"everywhere) load named exports fromlodash.I see the PR you mentioned is merged to node, so is there any change of revisiting this bug in
tsxnow?Currently blocked by https://github.com/nodejs/node/issues/51327
I investigated this and it might be tough to fix.
When a ESM file imports a CommonJS file, you would imagine a loader could simply transform the CommonJS file to ESM syntax on import so it’s interoperable.
However, Node.js actually bypasses the CJS loader and reads the CommonJS file directly from disk to statically detect named exports with
cjs-module-lexer.Static analysis is likely necessary because the import statement must assert that the named export exists before running the file. And even if Node.js adds a hook to transform the file before statically analyzing it, we won’t be able to support older Node.js versions.
I tackled this problem before (https://github.com/evanw/esbuild/issues/2248) but arrived at the same conclusion. However, I managed to fix it for dynamic imports.
Worth mentioning this bug prevents named imports from
lodash: https://github.com/privatenumber/tsx/issues/361Also, this is finally fixable when this lands in Node https://github.com/nodejs/node/issues/50839