Error: Unknown file extension ".ts" — running a TypeScript file directly with node
Plain `node file.ts` fails because Node doesn't transpile TypeScript by default. Use a runner like `tsx` or `ts-node`, or Node's built-in type-stripping support (`node --experimental-strip-types file.ts` on recent Node versions) for files that only use erasable type syntax.
What causes this error
Node's module loader picks a strategy based on file extension, and it has no built-in TypeScript-to-JavaScript transform for arbitrary syntax — type annotations, interfaces, and enums aren't valid JavaScript, so Node can't just execute the file as-is.
The Fix
# Option 1 — use a fast dedicated TypeScript runner
npx tsx file.ts
# Option 2 — ts-node (slower, but widely used in existing projects)
npx ts-node file.ts
# Option 3 — recent Node versions can strip simple, erasable type syntax
# natively without a build step (flag name/stability varies by version)
node --experimental-strip-types file.tsNative type-stripping only erases annotations — it does not support features that need real transformation, like enum, namespaces, or parameter properties in constructors. For those, stick with tsx/ts-node or compile with tsc first.
Common causes / variations
- Running a `.ts` script directly via `node` in a package.json `scripts` entry, copied from a project that used a bundler
- A CI pipeline invoking `node src/script.ts` without a transpile step
- Using enum/namespace syntax and expecting native type-stripping to handle it
Related errors
See also: ERR_REQUIRE_ESM, Cannot find module (missing extension in ESM).
Comments
Loading comments...