Search code examples
javascriptnode.jstypescript

Procedure for moving a NodeJS project to TypeScript


It seems that just installing it and then changing file extensions to .ts is not enough to effectively move to TypeScript with a NodeJS project. I get about 400 errors that seem to stem mostly from module resolution issues (but not only).

There are a couple of guides covering this topic, but they do not seem to help, maybe because they are one year old at best. Therefor, I want to ask for recent advice.

What steps do I need to take to transition a NodeJS project to Typescript?


Solution

  • 1.Add typings to your devDependencies in package.json

    {
      "devDependencies": {
        "typings": "latest"
      },
      "scripts": {
        "postinstall": "typings install --save"
      }
    }
    

    2.Add typings.json (alongside your package.json), note postinstall action in the package.json above - this will install typescript definitions upon each npm install

    {
      "globalDependencies": {
        "node": "github:DefinitelyTyped/DefinitelyTyped/node/node.d.ts"
      }
    }
    

    3.Add tsconfig.json

    { 
         "compilerOptions": { 
             "emitDecoratorMetadata": true, 
             "experimentalDecorators": true,
             "moduleResolution": "node",
             "module": "commonjs", 
             "target": "es6",
             "sourceMap": true,
             "outDir": "dist",
             "declaration": true,
             "allowJs": true,
             "forceConsistentCasingInFileNames": true
         },
         "exclude": [
             "node_modules",
             "dist",
             ".vscode",
             "docs"
         ]
    } 
    

    Note that allowJs option will help you to keep some javascript files unconverted if necessary.

    1. Make transpiling of ts files part of your build process

    This should get you going. After that step by step convert javascript to typescript in order to leverage its benefits.

    Hope this helps.