You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 11:20:28