Learn how to troubleshoot the "Unknown file extension '.ts'" error in Node.js and get your TypeScript projects up and running smoothly.
The error "TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension '.ts'" usually happens when you try to run TypeScript files (.ts) directly in Node.js. This is because Node.js only understands JavaScript (.js) files. To fix this, you need to convert your TypeScript code into JavaScript. There are a few ways to do this: you can use a tool like ts-node
to do it automatically during development, or you can compile your TypeScript code to JavaScript using the TypeScript compiler (tsc
) for production. Let's look at how to do both.
The error "TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension '.ts'" typically occurs when you're trying to use TypeScript files (.ts) directly with Node.js, especially in scenarios involving ES Modules (ESM). Here's a breakdown of why this happens and how to fix it:
Why the Error Occurs
require
and module.exports
). ESM (import
/export
) is the modern JavaScript module system. Mixing these can lead to issues.Solutions
Here are the most common ways to resolve this error:
Using ts-node
(For Development)
Installation: If you don't have it already, install ts-node
:
npm install -D ts-node typescript @types/node
Execution: Instead of running your file with node index.ts
, use ts-node
:
ts-node src/index.ts
(Replace src/index.ts
with your file path)
Explanation: ts-node
is a TypeScript execution engine and REPL for Node.js. It handles the transpilation of TypeScript to JavaScript on the fly, allowing you to run .ts
files directly.
Transpiling with tsc
(For Production)
Configuration: Create a tsconfig.json
file in your project root to configure the TypeScript compiler:
{
"compilerOptions": {
"target": "es2020", // Or your desired target
"module": "commonjs", // Or "esnext" for ESM
"outDir": "dist", // Output directory for compiled files
"esModuleInterop": true, // For better interoperability
"strict": true // Enable strict type checking
}
}
Compilation: Use the TypeScript compiler (tsc
) to transpile your code:
npx tsc
This will generate JavaScript files in the dist
directory (or as specified in tsconfig.json
).
Execution: Run the compiled JavaScript file with Node.js:
node dist/index.js
Using ESM with Node.js (Modern Approach)
Package.json: In your package.json
, add "type": "module"
to enable ESM:
{
"name": "my-project",
"version": "1.0.0",
"type": "module", // Enable ESM
// ... other settings
}
File Extensions: Use the .mjs
extension for your TypeScript files (e.g., index.mjs
) to signal that they are ESM modules.
tsconfig.json: Update your tsconfig.json
to target ESM:
{
"compilerOptions": {
// ... other options
"module": "esnext",
"outDir": "dist",
"esModuleInterop": true
}
}
Execution: You can now run your TypeScript files directly with Node.js:
node dist/index.mjs
Additional Tips
npm cache clean --force
or yarn cache clean
) and reinstalling dependencies can help.By following these steps, you should be able to resolve the "Unknown file extension '.ts'" error and run your TypeScript code successfully with Node.js.
This code demonstrates a simple TypeScript program that adds two numbers. It defines an add function in a separate file (math.ts) and imports it into the main file (index.ts). The code also provides instructions on how to run the program using ts-node for development, transpiling with tsc for production, or using ESM with Node.js.
// src/index.ts
import { add } from './math'; // If using ESM
const result = add(5, 3);
console.log(`5 + 3 = ${result}`);
// src/math.ts
export function add(a: number, b: number): number {
return a + b;
}
// --------------------------------------------------
// Running the code (choose one of the methods below)
// --------------------------------------------------
// 1. Using ts-node (for development)
// - Run: npx ts-node src/index.ts
// 2. Transpiling with tsc (for production)
// - Compile: npx tsc
// - Run: node dist/index.js
// 3. Using ESM with Node.js (modern approach)
// - Make sure you have "type": "module" in package.json
// - Rename index.ts to index.mjs
// - Compile: npx tsc
// - Run: node dist/index.mjs
Explanation:
src/index.ts
: This file contains your main application logic.
import { add } from './math';
: This line imports the add
function from the math.ts
file. If you are using CommonJS, you would use const { add } = require('./math');
instead.const result = add(5, 3);
: This line calls the imported add
function.console.log(...)
: This line prints the result to the console.src/math.ts
: This file contains a simple add
function.
export function add(...)
: The export
keyword makes the function available for import in other files. If you are using CommonJS, you would use module.exports = { add }
instead.Running the code: The comments in the code provide instructions for running the example using the three methods described in the article.
Important:
package.json
and tsconfig.json
: Make sure you have the necessary configurations in your package.json
(for ESM) and tsconfig.json
files as explained in the article..ts
file. Grasping the relationship between TypeScript (as a superset of JavaScript) and Node.js (a JavaScript runtime) is crucial for troubleshooting.ts-node
is Your Development Friend: While there are workarounds to directly execute .ts
files with Node.js, using ts-node
during development significantly streamlines the process. It provides a rapid feedback loop for coding and debugging..ts
, .js
, and .mjs
extensions is not arbitrary. They signal to Node.js and tools like ts-node
how to handle your code.This error happens because Node.js doesn't natively understand TypeScript (.ts) files. Here's a summary of the solutions:
Solution | Description | Use Case |
---|---|---|
ts-node |
Transpiles TypeScript on the fly. | Development: Quick and easy way to run .ts files directly. |
tsc (TypeScript Compiler) |
Transpiles TypeScript to JavaScript before execution. | Production: Generates optimized JavaScript code for deployment. |
ESM with Node.js | Configures Node.js to use the modern JavaScript module system. | Modern Projects: Enables direct execution of .mjs (ESM TypeScript) files. |
Quick Solutions:
ts-node
(npm install -D ts-node typescript @types/node
) and run your file with ts-node src/index.ts
.tsconfig.json
file, compile with npx tsc
, and run the generated JavaScript file with node dist/index.js
.Modern Approach (ESM):
"type": "module"
to your package.json
..mjs
extension for your TypeScript files."module": "esnext"
in your tsconfig.json
.node dist/index.mjs
.Troubleshooting:
In conclusion, encountering the "TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension '.ts'" error in your Node.js projects signifies a gap between TypeScript and how Node.js interprets files. Remember that Node.js natively executes JavaScript, not TypeScript. The solutions boil down to bridging this gap: either by using tools like ts-node
for on-the-fly transpilation during development or by employing the TypeScript compiler (tsc
) to generate JavaScript code for production environments. For modern projects, embracing ESM and configuring your project accordingly allows for direct execution of TypeScript files with the .mjs
extension. Understanding the distinction between development and production workflows, as well as the nuances of CommonJS and ESM, is crucial for choosing the most effective approach. By following the outlined solutions and tips, you can overcome this common hurdle and build robust Node.js applications with the power and flexibility of TypeScript.
Unknown file extension ".ts"
when running with mocha · Issue ... | In my tests, I only use import { expect } from "chai". npm run test (mocha) returns: TypeError: Unknown file extension ".ts" for /Users/me/git/myProj/test/app.test.ts at Object.getFileProtocolModul...ts-node
now it says ... | Posted by u/kriptonian_ - No votes and 10 comments