Webpack5 新功能 Module Federation 用法

438 阅读1分钟

Webpack5 新功能 Module Federation 用法

学习链接:

  1. blog.csdn.net/qq_41614928…

  2. developer.aliyun.com/article/755…

需要注意的是 vue-cli 的版本在5 以上才支持 webpack5 需要先查看vue-cli 的版本 :

$ vue -V

如果版本低 可以先 全局卸载

$ npm uninstall vue-cli -g

也可以查看当前所有版本:

$ npm view @vue/cli versions

image.png

选择 5以上的版本

或者直接安装最新版

$ sudo npm install @vue/cli -g

image.png

module federation 学习链接1中 详情修改参考

const { ModuleFederationPlugin } = require('webpack').container;
module.exports = {
  plugins: [
    new ModuleFederationPlugin({
      ...
    }),
  ],
};

针对 vue-cli 生成的项目 实现 Module Federation Demo

创建子应用提供组件模块

1 定义子应用 remote-vue-1 在子应用中添加 customModal.vue 组件

image.png

2 在vue.config.js 中配置

const { defineConfig } = require('@vue/cli-service');
const { ModuleFederationPlugin } = require('webpack').container;

module.exports = defineConfig({
  transpileDependencies: true,
  publicPath: 'http://localhost:8084/',  // 注意 配置publicPath
  chainWebpack: (config) => {
    config.optimization.delete('splitChunks'); // vue-cli 中启用了 splitChunks 会影响 在此关闭
  },
  configureWebpack: {
    plugins: [
      new ModuleFederationPlugin({
        name: 'home', // 必须,唯一 ID,作为输出的模块名,使用的时通过 ${name}/${expose} 的方式使用;
        filename: 'remoteEntry.js', // 构建出来的文件名
        exposes: { // 可选,表示作为 Remote 时,export 哪些属性被消费;
          './CustomModal': './src/components/customModal',
        },
      }),
    ],
    devServer: {
      port: 8084,
      hot: true,
    },
  },
});

3 可以通过build 查看打包后的结果

image.png

创建主应用 使用组件模块

1 定义主应用 并配置 vue.config.js

const { defineConfig } = require('@vue/cli-service');
const { ModuleFederationPlugin } = require('webpack').container;

module.exports = defineConfig({
  transpileDependencies: true,
  configureWebpack: {
    plugins: [
      new ModuleFederationPlugin({
        remotes: { // 可选,表示作为 Host 时,去消费哪些 Remote;
          home: 'home@http://localhost:8084/remoteEntry.js',
        },
      }),
    ],
    devServer: {
      port: 8085,
      hot: true,
    },
  },
});

2 在项目中引用 组件模块

image.png

3 查看效果

image.png