ts-node and mocha 'TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts"' error even with "ts-node/esm" loader and CommonJS modules

Viewed 8437

Before ask this question, I checked similar topics and tried typical solutions.

I know what the frequent cause is "module": "ESXXXX" in TypeScript configuration. In my case, I have error

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for D:\IntelliJ IDEA\XXXXXX\node_modules\tsconfig-paths\src\__tests__\config-loader.test.ts

in both "module": "ESnext" and "module": "CommonJS" cases.

One of typical solution is usage of ts-node/esm. First, this feature is experimental. Next, it just replace one error with another:

(node:24788) ExperimentalWarning: --experimental-loader is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)

× ERROR: CustomError: Cannot find module 'D:\IntelliJ IDEA\XXXXX\node_modules\tsconfig-paths\register' imported from D:\IntelliJ IDEA\XXXXX\node_modules\mocha\lib\nodejs\esm-utils.js

Versions

  • mocha: 9.2.1
  • ts-node: 10.7.0

Mocha config

extension:
  - ts

spec: "**/*.test.ts"

require:

  - ts-node/register
  - tsconfig-paths/register

loader: ts-node/esm # Tried with and without

4 Answers

Do you have a tsconfig.json. That solution could help here:

{
  "compilerOptions": {
    "esModuleInterop": true,
  }
}

Here is an interesting thread about it with an alternative solution. In that case, the tsconfig has an include that looks like this:

"include": [
    "./**/*.ts"
]

One of these two options should work, but let me know. Not sure what your config looks like.

i'm using same configuration like yours but it only work when i downgrade to ts-node@9, and then i tried this option in my .mocharc.json and now it's working as i expected

{
  "extensions": ["ts"],
  "spec": ["**/*.spec.*"],
  "node-option": [
    "experimental-specifier-resolution=node",
    "loader=ts-node/esm"
  ]
}

I added "type": "module" in package.json and did npx tsx file.ts instead of using ts-node file.ts and it worked.

Related