'ts-node and mocha 'TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts"' error even with "ts-node/esm" loader and CommonJS modules
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
Solution 1:[1]
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.
Solution 2:[2]
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"
]
}
Solution 3:[3]
I had the same error and it worked for me to set the NODE_OPTIONS env var to specify the loader:
NODE_OPTIONS="--loader ts-node/esm" mocha
Taken from here: https://typestrong.org/ts-node/docs/imports#native-ecmascript-modules
It might also help to upgrade to the latest version of ts-node 10.8.0
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | STh |
| Solution 2 | |
| Solution 3 | zrkl |
