Today I learned

Setting up Babel and TypeScript

A quick guide on setting up Babel as a TypeScript compiler

You can use Babel as a TypeScript compiler. This means much faster compilations, and you can use Babel plugins in TypeScript just as you would with JavaScript.

To do this, we'll configure tsc (the TypeScript compiler) only check types, but not emit files. We'll use Babel to do the actual compilation.

Installing packages

Install Babel and its required packages. We'll be using @babel/preset-typescript to allow Babel to consume TypeScript files, and typescript to check our types.

yarn add --dev \
  @babel/core \
  @babel/cli \
  @babel/preset-env \
  @babel/preset-typescript \
  typescript

Note: If you're already using a bundler like Webpack or Rollup, you may not need @babel/cli.

Configuration

Configure Babel

In babel.config.js, add the preset-typescript preset. This strips out type annotations from your TypeScript files, allowing Babel to compile them just as it would regular JavaScript.

babel.config.js
module.exports = {
  presets: [
    '@babel/preset-typescript',    '@babel/preset-env'  ]
}

This only makes Babel ignore the typesit doesn't check them! For that, we'll use TypeScript's tsc, which we'll get to later.

Configure TypeScript

Configure TypeScript by creating a file called tsconfig.json. Of particular interest here is noEmit, which prevents TypeScript from writing its own JavaScript files. We'll only be using TypeScript for type-checking. We'll leave the compilation duties to Babel.

tsconfig.json
{
  "compilerOptions": {
    "noEmit": true  }
}

Trying it out

Check types with tsc

Run tsc to check types. This should print a few errors if you have any.

yarn run tsc

Build files with babel

If you installed @babel/cli, you can test building files using the babel command. (Note: if you're using Webpack or Rollup, you don't need this package; use Webpack/Rollup to compile your JavaScript instead.)

yarn run babel src --out-dir lib --extensions '.ts,.tsx'

Configuring Babel-CLI

You can use Babel without Webpack or Rollup. If you're using already Webpack or Rollup, you can skip this; this is mostly ideal for writing small open-source libraries with limited compilation needs.

Auto-compile Babel files

You can use @babel/cli to compile files. In this example, we'll set up some NPM scripts to convert every TypeScript file in src/ to JavaScript files into lib/.

package.json
{
  "scripts": {
    "watch": "babel src --out-dir lib --extensions '.ts,.tsx' --watch",    "build": "babel src --out-dir lib --extensions '.ts,.tsx'",    "tsc": "tsc"
  }
}

References

This article was written for TypeScript 3.x and Babel 7.x. Here are some links for further reading:

You have just read Setting up Babel and TypeScript, written on April 10, 2019. This is Today I Learned, a collection of random tidbits I've learned through my day-to-day web development work. I'm Rico Sta. Cruz, @rstacruz on GitHub (and Twitter!).

← More articles