DrillLab
第 58 / 105 道58 / 105 · #337

React 项目里 babel 和 webpack 干什么

What do we use babel and web pack for in React applications

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

一句话分工:Babel 负责「翻译」(JSX 和新语法 → 浏览器能懂的 JS);Webpack 负责「打包」(把一堆模块和资源合并成能上线的几个文件)。

  • Babel——@babel/preset-react 转 JSX,@babel/preset-env按目标浏览器把 ES2020+ 降级。它只做语法转换, 新 API(PromiseArray.flat)要靠 polyfill 补。这个区分是加分点。
  • Webpack—— 解析 import 建依赖图、 让 CSS 和图片也能被 import、 tree shaking、代码分割、 开发时提供 dev server 和热更新。

顺序:Webpack 遇到 .jsx时调用 babel-loaderBabel 是 Webpack 流水线上的一个环节

会追问:「现在还用它们吗?」—— 这题答得出现状才显得在跟进: 新项目多用 Vite(开发用原生 ESM + esbuild, 生产用 Rollup),Babel 常被 esbuild / SWC 取代(快一个量级)。Webpack 仍在大量存量项目和 需要复杂定制的场景里。
我们这门课的 React 源项目用的就是 Vite —— 所以node_modules 里根本没有 webpack。

The split in one line: Babel translates (JSX and new syntax → JS the browser understands); Webpack bundles (a pile of modules and assets become the few files you ship).

  • Babel@babel/preset-react handles JSX, @babel/preset-env down-levels ES2020+ for your target browsers. It only transforms syntax; new APIs (Promise, Array.flat) still need a polyfill. Drawing that line scores points.
  • Webpack — reads your imports to build a dependency graph, lets you import CSS and images too, does tree shaking and code splitting, and gives you a dev server with hot reload while you work.

The order: when Webpack hits a .jsx file it calls babel-loader, so Babel is one stage of the Webpack pipeline.

Follow-up: “Are they still used?” — knowing the current state is what shows you keep up: new projects mostly reach for Vite (native ESM plus esbuild in development, Rollup for production), and Babel is often replaced by esbuild or SWC — an order of magnitude faster. Webpack is still everywhere in existing codebases and wherever heavy customisation is needed.
The React source project in this course uses Vite — which is why there is no webpack in its node_modules at all.