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

Most upvoted comments

Hi @privatenumber, I’ve just bumped into this issue trying to migrate a CJS project to ESM adding "type": "module" to its package.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 from lodash.

I see the PR you mentioned is merged to node, so is there any change of revisiting this bug in tsx now?

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/361

Also, this is finally fixable when this lands in Node https://github.com/nodejs/node/issues/50839