1.0.2 • Published 3 years ago
module-federation-helper v1.0.2
模块联邦拆分辅助工具
一、主要研发背景
- 使用webpack5的模块联邦把进行应用解耦时,各个模块之间存在互相依赖,需要工具对这些依赖进行管理,否则后面很难梳理
- 在进行实际打包时,需要把对应的产物放置到特定的位置。如果拆成了多个模块,要去批量改最终生成的位置等信息,容易出问题
- 需要有工具可以直观展示模块之间的依赖关系
- 模块增加、移除等会有联动,手动操作容易出错
二、使用方法
2.1 首先需要保证您的项目使用了webpack5进行构建
您可以选择以下方案对使用旧版webpack打包的项目进行webpack升级:
- 参照webpack官网,进行webpack版本及其相关依赖升级
- 先升级vue-cli相关脚手架,再应用其进行webpack升级
推荐使用方案2,这里不做赘述。
2.2 脚手架安装及初始化
1. 全局安装,进行配置文件初始化
安装:
npm i -g module-federation-helper
# 安装完成后,可以使用 --help 或者 -h,查看帮助文档
mfh --help
初始化:
mfh init
执行该命令,会询问一系列配置,您也可以使用 --yes 或者 -y 参数,直接跳过,走默认配置
mfh init --yes
执行完后,会在当前目录下生成 module-federation-helper-config.json 文件,您也可以手动对该文件进行修改(不建议)
module-federation-helper-config.json字段说明:
{
// 开发环境判断,如果判断到当前的 process.env.NODE_ENV 为这个配置值时,会直接返回所有的模块配置,以支撑开发环境调试
"devEnvName": "development",
// 打包命令script名称,例如下方配置,实际走打包时,会执行 npm run build
"buildScriptName": "build",
// dist目录下子模块放置的目录
"childModuleDistBasePath": "modules",
// 子模块的打包入口
"mainModuleEntryFilePath": "src/main.js",
// 主模块的打包入口
"childModuleEntryFilePath": "src/child-main.js",
// 临时生成打包产物的路径,一般不需要修改
"tempDistDirName": "node_modules/module_federation_micro_build_temp",
// 最终产物路径
"finallyDistDirName": "dist",
// 所有的已配置的模块
"modules": {},
// 当前配置的模块中的主模块(只允许有一个)
"mainModule": ""
}
2. 安装到项目的devDependencies下,并进行配置
安装依赖
npm i --save-dev module-federation-helper
vue.config.js 配置示例:
/* eslint-disable prettier/prettier */
const { defineConfig } = require('@vue/cli-service');
const webpack = require('webpack');
const { getModuleFederationConfig, getOutputDir, getPublicPath } = require('module-federation-helper');
const buildConfig = getModuleFederationConfig();
module.exports = defineConfig({
publicPath: getPublicPath(),
transpileDependencies: true,
productionSourceMap: false,
pages: {
index: {
// page 的入口
entry: buildConfig.entry,
// 模板来源
template: 'public/index.html',
// 在 dist/index.html 的输出
filename: 'index.html',
// 当使用 title 选项时,
// template 中的 title 标签需要是 <title><%= htmlWebpackPlugin.options.title %></title>
title: '子应用打包测试'
}
},
outputDir: getOutputDir(),
configureWebpack: {
plugins: buildConfig.pluginConfigs.map(config => new webpack.container.ModuleFederationPlugin(config))
}
});
package.json 中 scripts 打包脚本配置示例:
{
...
"scripts": {
// 只打包module-b模块
"micro-build:module-b": "mfh build module_b",
// 全量打包
"build:all": "mfh build --all"
}
...
}
2.3 主要命令
查看帮助使用 --help 或 -h
# 查看所有帮助
mfh -h
# 查看单个命令帮助,如 init
mfh init -h
主要命令
命令 | 功能 | 示例 |
---|---|---|
init options | 配置文件初始化 | mfh init -y |
create moduleName | 模块初始化 | mfh create test-module |
remote moduleName | 修改模块remote配置 | mfh remote test-module |
ls options | 列出模块配置 | mfh ls test-module |
rm-module moduleName | 删除模块配置 | mfh rm-module test-module |
expose moduleName | 模块修改expose导出 | mfh expose test-module |
rm-expose moduleName | 删除模块expose配置 | mfh rm-expose test-module |
build options | 模块打包 | mfh build --all |