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

React项目react-scripts build成功但craco build执行失败求助

解决CRACO + Module Federation构建报错问题

错误原因

报错TypeError: Cannot read properties of undefined (reading 'ModuleFederationPlugin'),本质是craco-module-federation插件无法正确获取到webpack 5的ModuleFederationPlugin,通常由依赖版本不兼容或插件未正确加载webpack实例导致。

解决方案

方案1:替换为手动配置Module Federation

无需依赖craco-module-federation插件,直接在craco.config.js中手动添加webpack插件配置,更稳定可控:

修改craco.config.js内容如下:

const webpack = require('webpack');
const deps = require("./package.json").dependencies;

module.exports = {
  webpack: {
    configure: (webpackConfig) => {
      // 添加Module Federation插件
      webpackConfig.plugins.push(
        new webpack.container.ModuleFederationPlugin({
          name: "transactionUi",
          exposes: {
              // 取消注释并配置需要暴露的组件
              // "./MyComp": "./src/components/App.js",
          },
          filename: "remoteEntry.js",
          shared: {
              ...deps,
              react: {
                  singleton: true,
                  requiredVersion: deps["react"],
              },
              "react-dom": {
                  singleton: true,
                  requiredVersion: deps["react-dom"],
              },
          },
        })
      );
      return webpackConfig;
    },
  },
};

之后可以删除单独的modulefederation.config.js文件,重新执行craco build即可。

方案2:修复依赖版本兼容性

  1. 卸载现有craco-module-federation:
npm uninstall craco-module-federation
  1. 安装最新兼容版本:
npm install craco-module-federation@latest
  1. 删除node_modules和package-lock.json,重新安装依赖:
rm -rf node_modules package-lock.json
npm install
  1. 再次执行craco build尝试构建。

方案3:锁定webpack版本

若项目中存在webpack版本冲突(比如依赖强制引入了webpack 4),在package.json中添加版本锁定:

"resolutions": {
  "webpack": "^5.0.0"
}

执行npm install后重新构建。

内容的提问来源于stack exchange,提问作者copenndthagen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 08:00:22