Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 38 ยท Entry, Output and Loaders

Babel and TypeScript Loaders

Compile modern JavaScript, JSX and TypeScript in Webpack with babel-loader, preset-env and browserslist, ts-loader or swc-loader, type checking with a separate plugin, and build caching.

Webpack reads modern JavaScript syntax itself (import, classes, async functions, optional chaining), but it does not compile it for old browsers, and it cannot read JSX or TypeScript. For that you add a transpiler as a loader. The three popular choices are Babel (babel-loader), the TypeScript compiler (ts-loader), and the fast Rust-based SWC (swc-loader).

babel-loader

Terminal
npm install --save-dev babel-loader @babel/core @babel/preset-env
JavaScript
{
  test: /\.m?js$/,
  exclude: /node_modules/,
  use: {
    loader: 'babel-loader',
    options: {
      presets: [['@babel/preset-env', { useBuiltIns: 'usage', corejs: 3 }]],
      cacheDirectory: true,
    },
  },
}

@babel/preset-env converts syntax your target browsers do not support. Which browsers is decided by browserslist, a list in package.json shared with PostCSS and other tools:

JSON
{
  "browserslist": ["defaults", "not dead", "> 0.5%"]
}

The smaller your target list, the less code Babel rewrites and the smaller the bundle. useBuiltIns: 'usage' adds only the polyfills your code actually needs (from core-js, which must be installed). cacheDirectory: true stores compiled files in node_modules/.cache so rebuilds skip unchanged files.

Exclude node_modules for speed, but remember that some packages ship untranspiled modern code. If one breaks an old target, add an include list for that package instead of removing exclude.

JSX with Babel

Add a preset for React:

JavaScript
presets: [
  '@babel/preset-env',
  ['@babel/preset-react', { runtime: 'automatic' }],
],

and extend the rule: test: /\.[jt]sx?$/. The automatic runtime means you do not import React in every file. If you use TypeScript with Babel, also add @babel/preset-typescript, which removes types but does not check them.

TypeScript with ts-loader

Terminal
npm install --save-dev typescript ts-loader
JavaScript
{
  test: /\.tsx?$/,
  use: 'ts-loader',
  exclude: /node_modules/,
}

and tell Webpack to resolve .ts files, otherwise import './app' will not find app.ts (Resolve and Aliases):

JavaScript
resolve: { extensions: ['.tsx', '.ts', '.js'] },

A minimal tsconfig.json for a bundler setup:

JSON
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "strict": true,
    "jsx": "react-jsx",
    "sourceMap": true,
    "noEmit": false
  },
  "include": ["src"]
}

Keep module as ESNext. If TypeScript turns imports into CommonJS require calls, Webpack cannot tree shake them (How a Bundler Works).

Type checking is slow: separate it

ts-loader both transpiles and type-checks, which slows rebuilds on large projects. A common recipe is to turn off type checks in the loader and run them in a parallel process with fork-ts-checker-webpack-plugin:

JavaScript
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');

module.exports = {
  module: {
    rules: [{
      test: /\.tsx?$/,
      loader: 'ts-loader',
      options: { transpileOnly: true },
    }],
  },
  plugins: [new ForkTsCheckerWebpackPlugin()],
};

Now the loader only strips types and compiles, which is fast, while the plugin reports type errors in the terminal without blocking compilation.

SWC and esbuild loaders

swc-loader and esbuild-loader do the same job as Babel or ts-loader in compiled languages (Rust and Go), often several times faster. Both only transpile and do not type-check.

JavaScript
{
  test: /\.[jt]sx?$/,
  exclude: /node_modules/,
  loader: 'swc-loader',
  options: {
    jsc: { parser: { syntax: 'typescript', tsx: true }, target: 'es2020' },
  },
}
Loader Strength Weakness
babel-loader huge plugin ecosystem, precise polyfills slowest
ts-loader full type checking slow on large projects unless transpileOnly
swc-loader fast, supports JSX and TypeScript smaller plugin ecosystem
esbuild-loader very fast, also a minifier fewer transforms

What "transpiling" means

A transpiler rewrites syntax into older syntax, keeping behavior. This stand-in does a tiny version of that for one feature, optional chaining, so you can see what Babel does for an older target. It is a toy regular expression, not a parser.

Node.js Stand-in: a tiny syntax transform

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

And a second stand-in for the "strip types only" idea used by transpileOnly and SWC:

Node.js Stand-in: stripping type annotations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which setting tells Babel which browsers to support?

    preset-env reads the browserslist configuration to decide which syntax to transform.
  2. 2. Why use ts-loader with transpileOnly plus ForkTsCheckerWebpackPlugin?

    Transpiling is quick; the type checker runs in parallel and reports errors without slowing rebuilds.
  3. 3. What does @babel/preset-typescript do with types?

    Babel erases type annotations; a separate tsc or plugin step is needed to check types.
  4. 4. Why should tsconfig use module ESNext in a Webpack project?

    Compiling imports to CommonJS would hide them from Webpack's static analysis.

Summary

  • babel-loader plus @babel/preset-env and browserslist compiles modern JS for your target browsers; use cacheDirectory.
  • ts-loader compiles TypeScript; add resolve.extensions for .ts/.tsx.
  • Separate type checking with transpileOnly and fork-ts-checker-webpack-plugin for speed.
  • SWC and esbuild loaders are faster transpilers that do not type-check.
  • Keep module: ESNext so tree shaking still works.

Next: Resolve, Extensions and Aliases