🐶
Node.js

Solve TypeScript Error: Unknown File Extension ".ts"

By Filip on 10/05/2024

Learn how to troubleshoot the "Unknown file extension '.ts'" error in Node.js and get your TypeScript projects up and running smoothly.

Solve TypeScript Error: Unknown File Extension ".ts"

Table of Contents

Introduction

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.

Step-by-Step Guide

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

  • Node.js and TypeScript: Node.js natively understands JavaScript (.js) files, not TypeScript (.ts) files. TypeScript needs to be transpiled (converted) into JavaScript before Node.js can execute it.
  • ESM and CommonJS: Historically, Node.js used CommonJS for modules (using 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:

  1. 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.

  2. 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 
  3. 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

  • Clear Cache: Sometimes clearing your package manager's cache (npm cache clean --force or yarn cache clean) and reinstalling dependencies can help.
  • IDE Configuration: Ensure your IDE (like VS Code) is properly configured for TypeScript and Node.js.
  • Check Node.js Version: Older Node.js versions might not have full ESM support. Consider upgrading to a recent version.

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.

Code Example

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:

  • Choose one method: Select the method that best suits your project's needs (development, production, or modern ESM).
  • 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.

Additional Notes

  • Understanding the "Why" is Key: The error message itself is quite descriptive – Node.js doesn't know what to do with a .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.
  • Production Requires a Build Step: For production environments, always transpile your TypeScript code to JavaScript. This ensures compatibility, optimizes performance, and avoids shipping your source code.
  • ESM is the Future, But Transition Carefully: ESM offers advantages over CommonJS, but migrating existing projects requires careful consideration and potential code adjustments.
  • File Extensions Matter: The use of .ts, .js, and .mjs extensions is not arbitrary. They signal to Node.js and tools like ts-node how to handle your code.
  • Keep Your Tools Updated: Node.js and TypeScript are actively developed. Keeping your versions up-to-date can prevent compatibility issues and give you access to the latest features.
  • Community is Your Resource: The error "TypeError [ERR_UNKNOWN_FILE_EXTENSION]" is common, and you'll find numerous resources online (Stack Overflow, GitHub issues, etc.) with solutions and explanations. Don't hesitate to search for help!
  • Experiment and Learn: The best way to solidify your understanding is to experiment with different configurations and approaches. Try creating a small TypeScript project and running it using the methods described in the article.

Summary

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:

  • Development: Install ts-node (npm install -D ts-node typescript @types/node) and run your file with ts-node src/index.ts.
  • Production: Create a tsconfig.json file, compile with npx tsc, and run the generated JavaScript file with node dist/index.js.

Modern Approach (ESM):

  1. Add "type": "module" to your package.json.
  2. Use the .mjs extension for your TypeScript files.
  3. Set "module": "esnext" in your tsconfig.json.
  4. Run your files directly with node dist/index.mjs.

Troubleshooting:

  • Clear your package manager's cache and reinstall dependencies.
  • Ensure your IDE is configured correctly for TypeScript and Node.js.
  • Use a recent Node.js version with full ESM support.

Conclusion

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.

References

Were You Able to Follow the Instructions?

😍Love it!
😊Yes
😐Meh-gical
😞No
🤮Clickbait