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

无需eject及CRACO配置,能否直接在create-react-app中用Webpack Module Federation插件?

在Create React App中无需eject使用Webpack Module Federation的方案

问题解答

可以不执行eject操作在Create React App(CRA)中使用Webpack Module Federation插件,也能做到无需eject且不依赖CRACO来适配现有项目,具体可行方案如下:


方案1:使用react-app-rewired + customize-cra

这是社区常用的非eject式修改CRA配置的方案,无需依赖CRACO:

  • 首先安装依赖:
    npm install react-app-rewired customize-cra --save-dev
    
  • 在项目根目录创建config-overrides.js文件,添加Module Federation配置:
    const { override, addWebpackPlugin } = require('customize-cra');
    const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin');
    
    module.exports = override(
      addWebpackPlugin(
        new ModuleFederationPlugin({
          name: 'yourAppName',
          filename: 'remoteEntry.js',
          exposes: {
            './YourComponent': './src/components/YourComponent',
          },
          remotes: {
            // 若需要引入其他联邦模块,在此配置
            // remoteApp: 'remoteApp@http://localhost:3001/remoteEntry.js',
          },
          shared: {
            react: { singleton: true, requiredVersion: '^18.2.0' },
            'react-dom': { singleton: true, requiredVersion: '^18.2.0' },
          },
        })
      )
    );
    
  • 修改package.json中的启动脚本,替换原有的react-scripts命令:
    "scripts": {
      "start": "react-app-rewired start",
      "build": "react-app-rewired build",
      "test": "react-app-rewired test"
    }
    
  • 启动项目即可生效,无需eject。

方案2:使用@module-federation/universe的CRA适配工具

这个工具包专门为CRA提供了Module Federation的低配置支持:

  • 安装依赖:
    npm install @module-federation/universe --save-dev
    
  • 在项目根目录创建modulefederation.config.js:
    module.exports = {
      name: 'yourAppName',
      filename: 'remoteEntry.js',
      exposes: {
        './YourComponent': './src/components/YourComponent',
      },
      shared: {
        react: { singleton: true },
        'react-dom': { singleton: true },
      },
    };
    
  • 修改package.json的启动脚本:
    "scripts": {
      "start": "mf start",
      "build": "mf build"
    }
    
  • 该工具会自动处理CRA的webpack配置注入,无需手动修改或eject。

方案3:手动fork并修改react-scripts

如果需要完全自主控制配置,可以fork官方的react-scripts仓库:

  • 克隆react-scripts到本地,找到其中的webpack配置文件(通常在config/webpack.config.js)
  • 在配置中添加ModuleFederationPlugin的实例
  • 将项目中的react-scripts依赖替换为本地fork的版本(通过package.json的file路径或私有npm包)
  • 这种方式无需eject,但需要维护自己的react-scripts分支,适合长期需要定制CRA配置的场景。

内容的提问来源于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 18:14:52