I'm working in TypeScript, using modern import statements. Running nodemon
(which then uses ts-node
) this obviously results in SyntaxError: Cannot use import statement outside a module
. Fair enough, so I added "type": "module"
to my package.json
file. Without changing anything else, the new error now reads: TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for .../file.ts
. Keep in mind that the exact same configuration - before adding "type":"module"
ran the .ts
files just fine. Nodemon is also still using ts-node correctly, as witnessed by the line above the error: [nodemon] starting ts-node src/file.ts
So I'm confused: Without using "type":"module"
and modern imports, everything works just fine. Adding modern imports adds a rightful error. Trying to fix that with "type":"module"
creates strange behavior though.
I also tried removing all content from my main .ts file, only adding a console.log statement. Without "type":"module"
in my package.json file, this prints to the log just fine. Adding "type":"module"
back immediately results in the unknown file extension error again.
Simply put:
This works fine:
// File.ts
console.log("test")
// package.json
{
...
}
// Output
test
This results in an error:
// File.ts
console.log("test")
// package.json
{
"type": "module",
...
}
// Output
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for .../file.ts
I'm sure I'm doing something wrong, but these kinds of errors don't really make it easy to figure out for yourself. Does anyone know what could be causing this?
tsc -w
in one shell thennodemon path/to/output.js
instead. – Yogurtnodemon
withts-node
is really just a pain to configure compared to two commandstsc -w
and then runningnodemon
on the output. – Yogurttype:module
in your package.json, or you try to use.mts
file extension, you can not anymore usets-node --esm
orts-node-esm
or{ ts-node: { esm: true } }
in your tsconfig.json. There is a workaround. Usenode --loader ts-node/esm myfile.mts
, but people in thread above report that line numbers in error stack trackes are broken then. Other solution: downgrade to node 18.x – Interlunation