JavaScript is the intelligence of the web, but it can be quite unhinged if not used with safety-gears, and TypeScript provides just that. Whenever we Web Devs start learning tinkering the website, we move from JavaScript to TypeScript, not the other way (usually). So, lots of times it actually occurs that, the initial projects of us are solely written in JavaScript.
But as we move to TypeScript eventually, it is natural to feel the need to migrate our old projects to TypeScript. Or, you’re a backend developer with the holy task of migrating the codebase to TypeScript, yes, many production grade applications are going with TypeScript now because of it’s deterministic nature throughout the codebase no matter how massive or complex it is.
But, as project structures vary with use-cases, complexity of it and the intention it was written with, so as the migration process. Anyways, it can be generalized enough to give a starting point ofcourse.
So, here’s the steps to how to migrate a project from JavaScript to TypeScript:
If you don’t wanna nuke your old, stable codebase, just create a separate branch (e.g. migrate/ts branch). You can always merge back to the original branch if the migration is complete and properly tested
# pull the latest main branch
$ git checkout main
$ git fetch origin
$ git pull
$ git checkout -b migrate/ts
The sole dependencies for migration to typescript is TypeScript and @types for the backend you’re using, for a typical Express based REST API:
$ npm install -D typescript @types/node @types/express
Now, generate a tsconfig.json with:
$ npx tsc --init
tsconfig.json contains all the necessary configurations for your typescript project, the essential changes are:
{
"compilerOptions" : {
// File Layout
"rootDir": "./src",
"outDir" : "./dist/",
// Environment Settings
"module": "nodenext",
"moduleResolution" : "nodenext",
"target" : "es2022",
"verbatimModuleSyntax": false,
},
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.d.ts"],
"exclude": ["dist"]
}
Note: the module and moduleResolution is set for modern ESM based syntax (with import support), and verbatimModuleSyntax is set to false so that TypeScript lint does not cry when you import your locally created modules with a .js extension.
Lastly, edit the package.json , adding the command for your tsc compiler:
{
// existing code...
"scripts": {
"dev": "tsc -b && node ./dist/index.js"
}
// existing code...
}