DEV Community

Cover image for Escape plan (from JS to TS) - Simple project - PART #1
Alexey Okhrimenko
Alexey Okhrimenko

Posted on

Escape plan (from JS to TS) - Simple project - PART #1

Here is a simple escape plan that will help you to move from old code base to modern TypeScript. This plan may not work for your project, but at least you can use it as a good starting point.

1) Move .js files to src folder (if not already)

2) For really old code base (ES3/ES5), apply Lebab (https://lebab.unibtc.me/). Lebal is an awesome tool to modernize your code base ES3/ES5 => ES2015/2016 automatically.

npx lebab --replace src/ --transform let,class,arrow,arrow-return,commonjs,template,obj-method,obj-shorthand ,for-of,for-each,arg-rest,arg-spread
Enter fullscreen mode Exit fullscreen mode

3) Rename extension of JS files to TS files

for file in src/**/*.js; do mv "$file" "${file%.*}.ts"; done

Enter fullscreen mode Exit fullscreen mode

4) Create webpack config with Webpack CLI. Don't forget to choose TS when asked

npx webpack-cli init
Enter fullscreen mode Exit fullscreen mode

5) Create tsconfig.json in root of your project. It's a loose config that will help you to start quickly. It will do for now.

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "resolveJsonModule": true,
    "downlevelIteration": true,
    "lib": ["es2015", "dom"],
    "module": "es6",
    "target": "es5",
    "allowJs": true,
    "strict": false
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "node_modules"
  ]
}
Enter fullscreen mode Exit fullscreen mode

6) If your code base doesn't have any import/require statements (you where using global scope and file concatenation). Add export to all top level function and classes, it will help us with the next step.

find src/ -name "*.ts" -exec sed -i '' "s/^function/export function/g;s/^class/export class/g" {} \;

Enter fullscreen mode Exit fullscreen mode

7) Use modern IDE (WebStorm, VSCode). Fix missing imports and property declarations. In any other hard to solve case use any. Do not worry. We will fix that later, in next post. Repeat until npm run build stops reporting errors.

Alt Text

Alt Text

8) PROFIT!

Realworld example

I used this plan to modify a game called unicorn-runner. If you interested on how code based changed thanks to that plan:

This is code before https://github.com/obenjiro/unicorn-runner/tree/fccc2f57470dde0f76850522c3e7e6abe8157789

This is after https://github.com/obenjiro/unicorn-runner/tree/88157915758c4c270fa64ccd4fd2427a68bcba7a

About PART #2

In the next part I will tell you how to add missing types automatically and make your tsconfig.json little bit stricter :)

Oldest comments (0)