Migrating a Babel project to TypeScript
If you’re building a web application today, you’re probably using the popular tool Babel to take advantage of the latest EcmaScript features (async/await, classes, destructuring, object spread, etc.) As your app grows, you might want better tooling to help with refactoring, autocompletion and possibly type safety. It was the case for us at Pleo, so we looked at switching from Babel to TypeScript.
Making the switch
To get started today with TypeScript, we will setup our project and update our webpack configuration.
We’ll start by installing typescript.
npm install --save-dev typescript
To setup the TypeScript compiler we’ll need to create a
tsconfig.json. Here are the minimal required settings:
The important part is
allowJs: true because we’ll use TypeScript to transpile our JS files, just like Babel is doing. We’ll set
checkJs: false because we don’t want TypeScript to start type checking our JS files just yet.
We’ll switch the babel-loader with a TypeScript loader (we chose awesome-typescript-loader) in our webpack configuration. We’ll also add sourcemap-loader to keep our sourcemaps. We’ll add
.tsx as extensions to be resolved, but we’ll keep
.jsx since we don’t want to migrate all of our files at once.
Next, we install awesome-typescript-loader and sourcemap-loader.
npm install --save-dev awesome-typescript-loader sourcemap-loader
And update our
webpack.config.js file like this:
We can now get rid of a bunch of babel dependencies!
That’s it! You made it, babel is replaced with TypeScript!
Converting files to TypeScript
Now that our development stack is ready, let’s take advantage of the great features of TypeScript. Let’s start with a simple React component and change it’s extension from
If we compile now, we will most likely end up with some errors. That’s because we’re missing some type definitions for React (or any other external module). Let’s fix this by installing the react type definitions. Definitions for third party libraries can be found on TypeSearch.
npm install --save-dev @types/react
Last thing we need is to be more explicit about our props. You might be used to `prop-types`, we’ll do something similar. Here’s an example:
SFC is the type of a React Stateless Functional Component and we pass the
AvatarProps interface which will do the PropTypes validation at compile time instead of runtime. This means better autocompletion on props, and no runtime errors or warnings!
With this file by file JS-TS migration we can now benefit from all the amazing features it has to offer like better code completions, strong type validations, go to definition and a lot more! This benefited us at Pleo by preventing a bunch of runtime errors, easier refactorings and better self-documenting code.