Create-React-App及所用Webpack各阶段是否优化node_modules依赖?
Great question! This is a super common point of confusion when working with Create-React-App (CRA) and its underlying Webpack setup, especially when dealing with large libraries like Lodash. Let's break this down step by step:
Development vs. Production Builds: What Gets Optimized?
- Development Mode (
npm start): Webpack's top priority here is fast rebuilds for hot reloading, not small bundle sizes. It doesn't run aggressive optimizations like tree shaking onnode_modulesdependencies. If you import the entire Lodash library, it'll bundle the whole thing—even if you only use_.map. Speed over size makes sense for development, where you're iterating constantly. - Production Mode (
npm run build): This is where heavy optimization kicks in. Webpack enables minification, dead code elimination, and tree shaking. But there's a critical catch: tree shaking only works reliably with ES Modules (ESM), not the older CommonJS module format.
Why import _ from 'lodash' Includes the Whole Library in Production
The default lodash npm package uses CommonJS modules under the hood. CommonJS doesn't support the static analysis Webpack needs to safely strip out unused code. So even in production builds, if you import the entire Lodash library like import _ from 'lodash', your bundle will include every single Lodash function—even the ones you never touch. That's around 70KB minified and gzipped, which adds unnecessary weight.
How to Only Bundle the Lodash Parts You Use
You have two straightforward ways to fix this and get proper tree shaking:
- Import individual methods directly: Skip importing the whole library and grab just the method you need:
This will only bundle theimport map from 'lodash/map';mapfunction and any internal dependencies it needs—way smaller! - Use
lodash-es(the ES Module version): Install thelodash-espackage, then import named methods:
Sinceimport { map } from 'lodash-es';lodash-esis built entirely with ESM, Webpack's production tree shaking will automatically strip out every unused Lodash method, leaving only the code you actually use.
What About Other node_modules Dependencies?
For other libraries that ship as ESM, Webpack's production build will automatically tree shake unused code. For CommonJS dependencies (like the default Lodash package), you'll run into the same issue—no effective tree shaking unless the library lets you import individual parts directly.
内容的提问来源于stack exchange,提问作者Siya Mzam

