What webpack does

webpack · Essentials · 8 min

Many production apps still build with webpack, and its concepts explain how all bundlers work.

Browsers load files over the network, while your code is split into hundreds of modules plus npm packages, CSS and images. A bundler turns that source tree into a few optimized files.

webpack works like this:

  • Start from one or more entry points (e.g. ./src/index.js).
  • Parse each module and follow its import, require() and import() calls to build the dependency graph. CSS, images and fonts can be part of the graph too.
  • Run each non-JavaScript (or non-plain-JavaScript) file through loaders, which turn it into modules webpack understands.
  • Group modules into chunks and emit them as bundles, with a small runtime that loads modules and chunks in the browser.
  • Plugins hook into every step for everything else: HTML generation, CSS extraction, minification, environment variables.

webpack 5 is extremely flexible, which is its strength and its cost: configuration can grow large, and builds are slower than Rust-based tools. New projects usually start with Vite or a framework's built-in tooling, while existing webpack apps often migrate to Rspack, a Rust reimplementation with a largely compatible API. The concepts in this course transfer directly to both.

The four core concepts to remember: entry, output, loaders, plugins, plus mode to choose development or production defaults.

Example

# Minimal setup: no config file needed for the defaults
mkdir wp-demo && cd wp-demo && npm init -y
npm install -D webpack webpack-cli
mkdir src
echo 'import { greet } from "./greet.js"; console.log(greet("Ann"));' > src/index.js
echo 'export const greet = (n) => `Hello, ${n}`;' > src/greet.js

npx webpack --mode production
# asset main.js 49 bytes [emitted] [minimized] (name: main)
# ./src/index.js + 1 modules ...
# webpack compiled successfully

node dist/main.js      # Hello, Ann

Remember

  • Entry -> dependency graph -> chunks -> bundles
  • Loaders transform files; plugins hook into the whole build
  • Defaults: entry ./src/index.js, output dist/main.js
  • Rspack offers a webpack-compatible, faster alternative

Watch out for

  • Starting a new project with a hand-written webpack config when a framework or Vite would do.

Check yourself

  1. What does webpack build before emitting any bundle?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: webpack.js.org/concepts/

Builds on

Nothing: this is a foundation.

Unlocks