Setting up Babel and TypeScript

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!

Display
The alien Babel fish can translate any language. This is not a babel fish.

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.

Setting it up

Install Babel

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.

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 types—it 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

Just 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/.

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

References