DrillLab
第 50 / 105 道50 / 105 · #283

Webpack 是怎么工作的

How does Webpack work

先自己答,再往下看Answer it yourself first

一句话:从入口出发递归分析所有 import, 建出一张依赖图, 路上用 loader 把各种文件转成 JS, 最后按规则打成若干个 bundle。

四个核心概念(必答):

  • entry—— 从哪开始找依赖。
  • output—— 打到哪里、叫什么名 (带 [contenthash] 做缓存)。
  • loader——把非 JS 转成 JSbabel-loader 转 JSX 和新语法、css-loader 让 CSS 能被importloader 是从右到左(从下到上)执行的, 这个细节常问。
  • plugin—— 在构建生命周期的各个钩子上干活, 能力比 loader 大得多 (生成 HTML、抽 CSS、压缩、分析体积)。

为什么需要打包(这才是问题的本质):浏览器早期不支持模块、 不认识 JSX 和 TS、 请求数多会慢; 打包解决的是模块化、转译、 合并压缩、以及 tree shaking

会追问:「Vite 为什么快?」—— 这题现在很常问。 开发时 Vite 不打包, 直接用浏览器原生 ESM 按需提供模块, 所以启动是常数时间, 不随项目变大而变慢; 依赖预构建用 esbuild(Go 写的,快一个量级); 生产才用 Rollup 打包。
Webpack 是「先全量打包再服务」, Vite 是「先服务再按需转换」—— 这一句就说到了根本区别。

In one line: start at the entry, walk every import recursively and build a dependency graph, push files through loaders to turn them into JS along the way, and emit a handful of bundles according to your rules.

Four core concepts you have to name:

  • entry — where the dependency walk starts.
  • output — where the bundles land and what they are called (with [contenthash] for caching).
  • loaderturns non-JS into JS. babel-loader handles JSX and new syntax, css-loader makes CSS importable. Loaders run right to left (bottom to top) — that detail gets asked a lot.
  • plugin — hooks into the build lifecycle and can do far more than a loader (generate HTML, extract CSS, minify, analyse bundle size).

Why bundling exists at all — that is the real question: early browsers had no modules, they do not understand JSX or TS, and a lot of requests is slow. Bundling buys you modularity, transpilation, merging and minifying, and tree shaking.

Follow-up: “Why is Vite fast?” — asked constantly now. In development Vite does not bundle; it serves modules on demand over the browser’s native ESM, so startup is constant time and does not degrade as the project grows. Dependency pre-bundling runs on esbuild (written in Go, an order of magnitude faster), and only production goes through Rollup.
Webpack bundles everything and then serves it; Vite serves first and transforms on demand — that single sentence gets at the fundamental difference.