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

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?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source