The error "TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension '.ts'" occurs when Node.js encounters a TypeScript (.ts
) file but doesn't recognize it natively, as Node.js only supports JavaScript (.js
) files by default. To run TypeScript files in Node.js, you need to transpile them to JavaScript first.
To resolve this issue, you can use a build tool like tsc
(TypeScript Compiler) or a bundler like Webpack or Babel to transpile your TypeScript files into JavaScript before executing them with Node.js.
Here's a step-by-step guide to resolve the error:
Install TypeScript: Make sure you have TypeScript installed in your project. If it's not installed, you can install it globally using npm:
bashnpm install -g typescript
Compile TypeScript to JavaScript: Before running your Node.js application, you need to compile your TypeScript files to JavaScript using the
tsc
command. If you haven't already, create atsconfig.json
file in the root of your project to specify TypeScript compilation options.json// tsconfig.json { "compilerOptions": { "target": "es6", "outDir": "./dist", "rootDir": "./src", "esModuleInterop": true } }
In this example, we are setting the
outDir
to./dist
, which means the compiled JavaScript files will be placed in thedist
directory. You may adjust this as per your project structure.Compile the TypeScript Files: Open your terminal, navigate to your project directory, and run the TypeScript compiler (
tsc
):bashtsc
This will transpile your TypeScript files into JavaScript files and place them in the specified
outDir
(e.g.,./dist
) as per yourtsconfig.json
.Run the Transpiled JavaScript Files: After successfully compiling your TypeScript files, you can run the transpiled JavaScript files using Node.js. For example:
bashnode ./dist/index.js
Replace
index.js
with the entry file of your Node.js application.
By following these steps, your TypeScript code will be transpiled into JavaScript, allowing Node.js to run it without encountering the "ERR_UNKNOWN_FILE_EXTENSION" error.