5

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?

Timmiej93
  • 1,328
  • 1
  • 16
  • 35
  • You might want to use `tsc -w` in one shell then `nodemon path/to/output.js` instead. – kelsny Apr 29 '22 at 17:18
  • @kellys Is that a known best practice, or just a workaround? – Timmiej93 Apr 29 '22 at 17:31
  • 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. – kelsny Apr 29 '22 at 17:32
  • 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? – Andy May 24 '23 at 14:45

0 Answers0