Unknown file extension error after adding 'type: module' to package.json
Asked Answered
C

0

6

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?

Circumstantial answered 29/4, 2022 at 15:42 Comment(6)
You might want to use tsc -w in one shell then nodemon path/to/output.js instead.Yogurt
@kellys Is that a known best practice, or just a workaround?Circumstantial
In my experience nodemon with ts-node is really just a pain to configure compared to two commands tsc -w and then running nodemon on the output.Yogurt
Appreciate the work around, but I find it incredible that ts-node doesn't actually do the one thing it is supposed to do. The lack of answers to this question suggests that its not that common a problem so how are people getting this to work?Neurovascular
There is a bigger issue with ts-node and node version 20.x / 21.x when using ESM loader: github.com/TypeStrong/ts-node/issues/1997 This means, whenever you have type:module in your package.json, or you try to use .mts file extension, you can not anymore use ts-node --esm or ts-node-esm or { ts-node: { esm: true } } in your tsconfig.json. There is a workaround. Use node --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.xInterlunation
See also https://mcmap.net/q/1517870/-use-ts-node-to-run-mts/…Interlunation

© 2022 - 2024 — McMap. All rights reserved.