tsc transpiles a script but neither ts-node nor tsx runs it

1 day ago 1
ARTICLE AD BOX

Why are there cases where tsc transpiles a certain script correctly, but neither ts-node nor tsx work?

For example, I have an ESM typescript that is importing from a CommonJS module:

// ./script.ts import { mysymbol } from "mymodule";

Running npx tsc transpiles the script correctly, no warnings given. It just works.

However, running either npx tsx ./script.ts or node -r ts-node/register --loader ts-node/esm ./script.ts does not work. The former gives:

SyntaxError: The requested module 'mymodule' does not provide an export named 'mysymbol'

The latter gives:

SyntaxError: Named export 'mysymbol' not found. The requested module 'mymodule' is a CommonJS module, which may not support all module.exports as named exports. CommonJS modules can always be imported via the default export, for example using: import pkg from 'mymodule'; const { mysymbol } = pkg;

This is extremely confusing.

Indeed following the recommendation makes it work, but I am puzzled -- the question is, why does the TypeScript transpiler work where the TypeScript runners don't? What is the difference?

I believed the TypeScript runners (ts-node, etc.) would simply transpile the project on the background/in-memory, or something akin to that. It definitely should work, at least conceptually.

package.json has type: module, this is intended. I want my scripts to be ESMs.

And tsconfig.json is just:

"compilerOptions": { "strict": true, "module": "nodenext", "target": "esnext" }
Read Entire Article