Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 38 ยท Webpack with Frameworks

Webpack with TypeScript

Compile TypeScript with webpack using ts-loader, babel-loader or swc-loader, set up tsconfig for bundlers, run type checks in parallel with fork-ts-checker, and resolve path aliases.

TypeScript adds static types to JavaScript, but browsers only run JavaScript. In a webpack build, a loader removes the types (and compiles newer syntax) while webpack bundles the result. There are three common ways to wire it: ts-loader (the official TypeScript compiler), babel-loader with the TypeScript preset, and swc-loader or esbuild-loader (very fast native compilers). They differ mainly in one respect: whether they check types or only strip them.

This lesson explains the options, a good tsconfig.json for bundled projects, how to get fast builds and type safety, and how to handle path aliases. The language itself is covered in the TypeScript tutorial.

Webpack is not runnable on the site, so configs are read-only. The TryIt blocks are Node.js stand-ins for the two jobs: stripping types, and checking them in a separate pass that runs in parallel.

Option 1: ts-loader

Terminal
npm install -D typescript ts-loader webpack webpack-cli
JavaScript
// webpack.config.js (read-only example)
module.exports = {
  entry: './src/index.ts',
  resolve: { extensions: ['.ts', '.tsx', '.js'] },
  module: {
    rules: [
      { test: /\.tsx?$/, exclude: /node_modules/, loader: 'ts-loader' },
    ],
  },
};

ts-loader runs the real TypeScript compiler: it reports type errors in the build output and uses your tsconfig.json. The cost is speed, since type checking is slow on large projects.

Option 2: transpile only, check separately

The modern approach separates concerns. A fast loader removes types without checking them, and a separate process does the type checking:

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

module.exports = {
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader',     // or 'swc-loader' / 'esbuild-loader'
        options: { presets: ['@babel/preset-env', '@babel/preset-typescript'] },
      },
    ],
  },
  plugins: [new ForkTsCheckerWebpackPlugin()],
};

ForkTsCheckerWebpackPlugin runs the TypeScript checker in a separate process, so the bundle is produced quickly while errors still appear (and fail the build in CI). With ts-loader you can get the same effect using the option transpileOnly: true plus the checker plugin.

Stripping types

When a loader only strips types, it deletes annotations, interfaces and type aliases and keeps the runtime code. Here is a deliberately naive stand-in.

Node.js Stand-in: strip 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.

The output runs without a compiler because the types were only for humans and tools. Notice what a type-stripper cannot do: it never notices that greet(5, 'x') is wrong.

A parallel checker

The next stand-in imitates the structure: a fast transpile step and a slower check that runs concurrently, with the build reporting both.

Node.js Stand-in: fast transpile, checker runs in parallel

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.

In development you see the bundle quickly and errors appear shortly after in the terminal or overlay. In CI, fail the build if the checker reports errors.

tsconfig.json for bundlers

When a bundler resolves imports and emits the output, TypeScript should only check types:

JSON
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "strict": true,
    "noEmit": true,
    "isolatedModules": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "jsx": "react-jsx",
    "baseUrl": ".",
    "paths": { "@/*": ["src/*"] }
  },
  "include": ["src"]
}
  • module: "ESNext" keeps import/export for tree shaking.
  • moduleResolution: "bundler" matches how bundlers resolve extensionless imports.
  • isolatedModules: true forbids constructs that a single-file transpiler cannot handle (such as re-exporting a type without export type). It is required when Babel, SWC or esbuild do the transpiling.
  • noEmit: true because the loader, not tsc, produces JavaScript. With ts-loader you may need to remove it.

Path aliases

paths in tsconfig.json only teaches the type checker about aliases such as @/utils/format. Webpack needs to know too:

JavaScript
const path = require('path');
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');

module.exports = {
  resolve: {
    extensions: ['.ts', '.tsx', '.js'],
    alias: { '@': path.resolve(__dirname, 'src') },
    // or: plugins: [new TsconfigPathsPlugin()],
  },
};

Keep both in sync, or let the plugin read the paths so you maintain them in one place.

Declaration files and assets

Importing a .css or .svg file in TypeScript fails type checking unless you declare the module:

TypeScript
// src/types/assets.d.ts
declare module '*.svg' {
  const url: string;
  export default url;
}
declare module '*.module.css' {
  const classes: Record<string, string>;
  export default classes;
}

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main difference between ts-loader (default) and babel-loader with preset-typescript?

    Babel, SWC and esbuild remove types without checking them. ts-loader uses the real compiler and reports type errors.
  2. 2. What does fork-ts-checker-webpack-plugin do?

    It performs type checking in parallel so transpile-only builds stay fast while errors are still reported.
  3. 3. Why is isolatedModules: true recommended with Babel or SWC?

    A transpiler sees one file at a time, so isolatedModules makes TypeScript reject code that needs cross-file type information to compile correctly.
  4. 4. Paths in tsconfig.json are set but webpack cannot find '@/utils'. What is missing?

    tsconfig paths only inform the type checker. Webpack needs its own alias or the plugin that reads them.

Summary

  • Use ts-loader for simplicity or a transpile-only loader (Babel, SWC, esbuild) for speed.
  • Add fork-ts-checker-webpack-plugin so types are still checked.
  • For bundlers use module: ESNext, moduleResolution: bundler, isolatedModules and noEmit.
  • Mirror paths aliases in webpack's resolve.alias, and declare modules for asset imports.

Next: Module Federation