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

Module Federation 请求远程组件时出现源地址错误问题

问题:Next.js Module Federation 远程组件资源地址错误

我在Next.js中使用Module Federation插件,现有host(http://localhost:3000)和calc(http://localhost:3001)两个应用。访问calc应用时,尝试加载host的远程组件,浏览器请求的资源源地址不正确。

相关截图

截图1
截图2

calc应用的nextjs.config.js配置

const { NextFederationPlugin } = require('@module-federation/nextjs-mf');
const path = require('path');

module.exports = {
  basePath: '/calc',
  webpack(config, options) {
    if (!options.isServer) {
      config.plugins.push(
        new NextFederationPlugin({
          name: 'calc',
          filename: 'static/chunks/remoteEntry.js',
          remotes: {
            host: `host@http://localhost:3000/v2/_next/static/chunks/remoteEntry.js`,
          },
          exposes: {},
          shared: {},
          publicpath: 'auto',
        }),
      );
    }

    return config;
  },
};
解决方案

问题出在两个核心配置错误:

  1. remote地址与host实际路径不匹配:先检查host应用的next.config.js是否配置了basePath: '/v2'。如果host没有设置该前缀,必须把calc配置中remotes的地址改为host@http://localhost:3000/_next/static/chunks/remoteEntry.js,否则会请求不存在的路径。
  2. publicPath拼写错误:插件配置里的publicpath应为驼峰式的publicPath(大写P),拼写错误会导致Module Federation无法正确计算远程资源的加载路径。

修正后的calc应用nextjs.config.js:

const { NextFederationPlugin } = require('@module-federation/nextjs-mf');
const path = require('path');

module.exports = {
  basePath: '/calc',
  webpack(config, options) {
    if (!options.isServer) {
      config.plugins.push(
        new NextFederationPlugin({
          name: 'calc',
          filename: 'static/chunks/remoteEntry.js',
          // 根据host实际basePath调整地址,示例为无basePath的情况
          remotes: {
            host: `host@http://localhost:3000/_next/static/chunks/remoteEntry.js`,
          },
          exposes: {},
          shared: {},
          // 修正拼写错误:publicpath → publicPath
          publicPath: 'auto',
        }),
      );
    }

    return config;
  },
};

额外注意:确保host应用的Module Federation配置正确暴露了组件,且remoteEntry.js的路径与calc配置一致。比如host的配置需包含:

new NextFederationPlugin({
  name: 'host',
  filename: 'static/chunks/remoteEntry.js',
  exposes: {
    './TargetComponent': './components/TargetComponent.js', // 明确要暴露的组件路径
  },
  // 如果host确实配置了basePath,这里要同步设置basePath: '/v2'
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 18:33:22