Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 573
Ludwik Avatar asked Jul 16 '16 18:07

Ludwik


2 Answers

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.

like image 55
Amid Avatar answered Nov 03 '22 07:11

Amid


Migrating Js to TS

You create a tsconfig.json with allowJs set to true. This allows you to use the .js as it is!. Next you start changing the file extension from .ts to .js one by one, declaring what you find missing as you go along.

I did a video about this about a week ago https://www.youtube.com/watch?v=gmKXXI_ck7w

More :

maybe because they are one year old at best.

I keep this up to date : https://basarat.gitbooks.io/typescript/content/docs/types/migrating.html

Of course if you read it as a book I assume you already have seen the nodejs quickstart : https://basarat.gitbooks.io/typescript/content/docs/quick/nodejs.html

like image 44
basarat Avatar answered Nov 03 '22 09:11

basarat