ts-node: ERR_UNKNOWN_FILE_EXTENSION after adding "type": "module" to package.json
I tried to create a test file to test the structure of my typescript code.
test/index.ts
import Player from "../models/Player";
const testplayer = new Player();
When i executed it, i got this error:
import Player from "../models/Player";
^^^^^^
SyntaxError: Cannot use import statement outside a module
After a bit of research, I found this issue which suggested adding "type": "module"
to the package.json. After I did this, i got the following error:
node:internal/process/esm_loader:74
internalBinding('errors').triggerUncaughtException(
^
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for XXX/test/index.ts
How can I run my file now? I am using ES6 (?) imports in the Player class: export default class Player {}
Specifications
- ts-node version: 9.1.0
- node version: 15.3.0
- TypeScript version: 4.1.2
- Operating system and version: macOS Catalina
About this issue
- Original URL
- State: closed
- Created 4 years ago
- Reactions: 21
- Comments: 16
Node’s documentation has everything you need.
I am having the same issue:
However,
"module": "commonjs"
doesn’t work for me.Typically you should have your tsconfig set to
"module": "CommonJS"
so that imports are compiled into commonjs calls. Then you don’t need to mess with node’s ESM loader. This is probably what you want: use"module": "CommonJS"
@realmayus let me know if this works or not.
any solution? I am facing same problem
use
node --loader ts-node/esm ./my-script.ts
insteadts-node ./my-script.ts
after i added
"type": "module"
, when runnpm run dev
, i got thishttps://github.com/TypeStrong/ts-node/tree/main/esm-usage-example
https://nodejs.org/api/esm.html#json-modules
Node has restrictions about JSON files in ESM, maybe you’re hitting that.
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension “.json” for D:\Installations\laragon\www\wp-pre-theme\wp-content\themes\firsttheme\package.json at Loader.defaultGetFormat [as _getFormat] (internal/modules/esm/get_format.js:71:15) at Loader.getFormat (internal/modules/esm/loader.js:102:42) at Loader.getModuleJob (internal/modules/esm/loader.js:231:31) at async ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:58:21) at async Promise.all (index 10) at async link (internal/modules/esm/module_job.js:63:9) { code: ‘ERR_UNKNOWN_FILE_EXTENSION’
Thanks, that worked 👍