← Back to TypeScript Course | Chapter 25: Build Tools | Lesson 1 of 6

Webpack with TypeScript

Webpack bundles TypeScript applications into browser-ready assets. TypeScript usually checks types separately while Webpack handles module bundling.

Core Concept

Webpack is a module bundler that walks your import graph starting from an entry file and packs everything into optimized output bundles; with TypeScript it needs the ts-loader (or babel-loader with the TypeScript preset) to compile .ts files as part of that bundling process.

Example: Core Concept

typescript
// webpack bundles from an entry file, using ts-loader to compile .ts files
console.log("Webpack needs ts-loader (or babel-loader) to handle TypeScript");

Basic Setup

A minimal setup adds ts-loader and typescript as dev dependencies, configures a module.rules entry matching /\.tsx?$/, and resolves .ts/.tsx extensions alongside .js in resolve.extensions.

Example: Basic Setup

typescript
// webpack.config.js
// module: { rules: [{ test: /\.tsx?$/, use: "ts-loader" }] }
// resolve: { extensions: [".ts", ".tsx", ".js"] }
console.log("ts-loader compiles .ts files as part of the bundle process");

Typed Example

A typed webpack config file itself can be written in TypeScript (webpack.config.ts) using the Configuration type from the webpack package, so a typo in a config key is caught before you even run the build.

Example: Typed Example

typescript
// webpack.config.ts
// import { Configuration } from "webpack";
// const config: Configuration = { entry: "./src/index.ts" };
console.log("Typed webpack.config.ts catches config typos at compile time");

Project Usage

In a real project, webpack handles code-splitting typed feature modules into separate chunks loaded on demand, keeping the initial bundle small while still type-checking every module before it ships.

Example: Project Usage

typescript
// import(/* webpackChunkName: "settings" */ "./settings").then(...)
console.log("Webpack code-splits typed modules into on-demand chunks");

Best Practices

Enable ts-loader's transpileOnly option with a separate fork-ts-checker-webpack-plugin for type checking, so full project type errors don't slow down every incremental rebuild during development.

Example: Best Practices

typescript
// ts-loader: { transpileOnly: true } + fork-ts-checker-webpack-plugin
console.log("Separate type checking from transpilation for faster rebuilds");
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.