Webpack 5构建的React组件库无法Tree Shake问题求助
问题:Webpack构建React组件库Tree Shaking失效,改用Rollup解决
问题场景
使用Webpack 5.75.0构建了一个React组件库,库中导出ComponentA和ComponentB两个组件。在未修改配置的CRA项目中仅引入ComponentA,但分析打包产物时发现ComponentB的依赖未被Tree Shake移除。
已尝试的无效配置
- 在
package.json中设置"sideEffects": false,并指定main和module字段 - 配置Babel开启ES Module输出(
@babel/preset-env设置modules: false) - Webpack 5配置开启ES Module输出(
output.module: true、library.type: "module"、experiments.outputModule: true)
相关配置代码
src/index.ts
export { default as ComponentA } from "components/ComponentA"; export { default as ComponentB } from "components/ComponentB";
package.json 关键配置
"sideEffects": false, "main": "lib/index.js", "module": "lib/index.js",
Babel配置(babel.config.js)
module.exports = { presets: [ ["@babel/preset-env", { targets: { node: "current", modules: false } }], "@babel/preset-typescript", [ "@babel/preset-react", { runtime: "automatic", }, ], ], plugins: [ "@babel/plugin-syntax-jsx", [ "@babel/plugin-transform-runtime", { regenerator: true, useESModules: true, }, ], ], };
Webpack配置
const config = { mode: "production", devtool: false, entry: "./src/index.ts", output: { path: path.resolve(__dirname, "lib"), filename: "index.js", module: true, library: { type: "module", }, }, externals: ["react", "react-dom"], experiments: { outputModule: true }, optimization: { minimize: false }, };
最终解决方案
改用Rollup构建组件库后,Tree Shaking正常生效,ComponentB的依赖被正确移除。
补充:Webpack 5自2021年起已支持ES Module构建,但本次场景下未达到预期的Tree Shaking效果。
内容的提问来源于stack exchange,提问作者Alexander Mikhalchenko
相关产品推荐
相关产品推荐

