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.
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.
Note: If you're already using a bundler like Webpack or Rollup, you may not need
@babel/cli
.
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.
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 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.
tsc
Run tsc
to check types. This should print a few errors if you have any.
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.)
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.
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/
.
This article was written for TypeScript 3.x and Babel 7.x. Here are some links for further reading: