Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ts-node TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts"

I am using ts-node but it is giving me this error:

$ ts-node index.ts

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /home/projects/node-hddds8/index.ts

I tried to remove "type": "module" from my package.json but in that case I get a different error:

$ ts-node index.ts

(node:45) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
/home/projects/node-hddds8/index.ts:1
import chalk from 'chalk';
^^^^^^

SyntaxError: Cannot use import statement outside a module

Here is a reproduction link on StackBlitz: https://stackblitz.com/edit/node-hddds8?file=index.ts

My package.json looks like this:

{
  "name": "node-starter",
  "version": "0.0.0",
  "type": "module",
  "dependencies": {
    "chalk": "^5.0.1",
    "ts-node": "^10.8.1",
    "typescript": "^4.7.4"
  }
}

And my tsconfig.json looks like this:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "moduleResolution": "Node",
  }
}

And my index.ts looks like this:

import chalk from 'chalk';

console.log(chalk.blue('Hello world!'));
like image 769
martins16321 Avatar asked Sep 03 '25 16:09

martins16321


2 Answers

Since you have "type": "module" in your package.json you are using ESM modules, therefore you need to add this to your tsconfig.json:

{
    "compilerOptions": {
        "module": "ESNext" // or ES2015, ES2020
    },
    "ts-node": {
        // Tell ts-node CLI to install the --loader automatically
        "esm": true
    }
}
like image 133
RcoderNY Avatar answered Sep 05 '25 05:09

RcoderNY


While the solutions with ts-node-esm or adding esm: true to the ts-node options in tsconfig works with "older" node versions, with node >= 20, this fails again with ERR_UNKNOWN_FILE_EXTENSION.

A workaround is to use node --loader as described in this issue:

node --no-warnings=ExperimentalWarning --loader ts-node/esm file.ts
like image 30
Martin Adámek Avatar answered Sep 05 '25 07:09

Martin Adámek