Webpack 5 Module Federation共享库问题:单例类重复实例化
模块联邦共享单例模块重复实例化问题排查及解决方案
容易遗漏的排查点
- 导入路径必须完全一致:宿主和远程应用对目标npm模块的导入写法要一模一样,比如不能一个用
import XXX from 'xxx',另一个用import XXX from 'xxx/dist/main'。哪怕路径差一点点,webpack模块联邦都会把它们当成两个不同模块,自然会生成两个实例。 - 共享配置的模块名称要统一:宿主和远程的
shared配置里,该模块的名称必须完全相同,比如都写'your-singleton-module',别一个用包名,另一个用webpack别名。 - 别让splitChunks拆分共享模块:如果你的webpack配置里splitChunks规则把这个共享模块拆成了多个chunk,单例肯定会失效。要确保splitChunks不会对这个模块动手。
- eager配置要两边都加:
eager: true不能只在宿主或者只在远程配置,必须两边的shared里都设置,否则可能加载时机不一致导致重复实例化。 - 清缓存试试:开发环境下webpack的缓存可能残留旧的模块实例,直接删了
node_modules/.cache或者重启dev server,说不定就能解决。
可运行的示例配置
宿主应用webpack.config.js核心代码
const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin'); module.exports = { plugins: [ new ModuleFederationPlugin({ name: 'hostApp', remotes: { remoteApp: 'remoteApp@http://localhost:3001/remoteEntry.js', }, shared: { 'your-singleton-package': { singleton: true, requiredVersion: '1.0.0', eager: true, }, }, }), ], };
远程应用webpack.config.js核心代码
const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin'); module.exports = { plugins: [ new ModuleFederationPlugin({ name: 'remoteApp', filename: 'remoteEntry.js', exposes: { './SharedComponent': './src/SharedComponent', }, shared: { 'your-singleton-package': { singleton: true, requiredVersion: '1.0.0', eager: true, }, }, }), ], };
单例模块示例(your-singleton-package/src/index.js)
class AppSingleton { constructor() { this.identity = Date.now(); } getIdentity() { return this.identity; } } // 直接导出实例,确保单例 const singletonInstance = new AppSingleton(); export default singletonInstance;
宿主与远程的使用方式
// 宿主应用入口文件 import singleton from 'your-singleton-package'; console.log('Host instance ID:', singleton.getIdentity()); // 远程应用的SharedComponent.js import singleton from 'your-singleton-package'; console.log('Remote instance ID:', singleton.getIdentity());
正常情况下,两次打印的ID应该完全相同,说明单例生效。
内容的提问来源于stack exchange,提问作者Johnny
相关产品推荐
相关产品推荐

