构建生产版React项目时Webpack默认开启Tree Shaking吗?
React生产构建中Webpack的Tree Shaking默认状态
Great question! Let's break this down clearly for you:
If you're using Create React App (CRA)—the official, most common way to start a React project—then yes: when you run npm run build to generate a production bundle, Webpack does have Tree Shaking enabled by default.
Why and how this works:
- CRA’s pre-configured Webpack setup includes production-ready optimizations out of the box, and Tree Shaking is a core part of that suite.
- Tree Shaking relies entirely on ES module syntax (
import/export), which CRA uses exclusively by default. This lets Webpack track exactly which exported values are actually used in your codebase. - During the production build, Webpack first flags unused exports as "dead code", then collaborates with the TerserPlugin (CRA’s default minifier) to strip that dead code from your final bundle.
A quick note for custom Webpack setups:
If you’re not using CRA and have a manually configured Webpack project for React, Tree Shaking won’t work automatically. You’ll need to ensure these key settings:
- Set
mode: 'production'in your Webpack config (this enables default optimizations including Tree Shaking). - Stick strictly to ES modules (
import/export) instead of CommonJS (require)—Tree Shaking can’t analyze dynamic CommonJS module loading. - Confirm a minifier like TerserPlugin is enabled (it’s included by default in production mode, but worth verifying if you’ve modified your config).
内容的提问来源于stack exchange,提问作者MII
相关产品推荐
相关产品推荐

