微前端架构方案:
1. 自由组织模式
System.js模块化
3. 基座模式
类似于qiankun,即有一个大盒子作为基座,所有子项目在其中加载展示。
4. 去中心模式(webpack5 Federated Module 联邦模块)
各项目可以相互使用对方的东西。
模块联邦
1.使用webpack启动服务,不通过vue-cli搭建项目
在项目根目录下,添加webpack.config.js,引入webpack(5版本)模块联邦,配置插件
app1:
webpack.config.js
const Mfp = require("webpack/lib/container/ModuleFederationPlugin") ; // 引入模块联邦
module.exports = {
publicPath: "/app1/",
devServer: {
port: 1001
}
...
plugins: [
new Mfp({
// 模块名称,唯一性,不能重名
name: 'app1',
// 打包的模块文件名
filename: 'remoteEntry.js',
// 当前模块具体暴露出去的内容
exposes: {
'./demo': './src/components/demo.vue'
},
// 公共模块,避免多次加载重复依赖
shared: require("./package.json").dependencies,
})
]
}
app2:
webpack.config.js
{
plugins: [
new Mfp({
// 模块名称,唯一性,不能重名
name: 'app2',
// 打包的模块文件名
filename: 'remoteEntry.js',
/**
引入远程模块
第一个app1是起的别名,可任意取名
app1@http://localhost:1001/lh/demo1/remoteEntry.js
-- app1是模块名称(上面的name)
-- @ 是固定写法
-- 服务地址+模块文件名(上面的filename)
*/
remotes: {
'app1':'app1@http://localhost:1002/app1/remoteEntry.js'
}
// 公共模块,避免多次加载重复依赖
shared: require("./package.json").dependencies,
})
]
}
bootstrap.ts
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import { defineAsyncComponent } from "vue";
const t = defineAsyncComponent(() => import("demo1/hello"));
const app = createApp(App);
app.component("MfT", t);
app.use(router).mount("#app");
main.ts
import(/* webpackChunkName: "main-bootstrap" */ "./bootstrap");
2.vue-cli搭建项目
在项目根目录下,vue.config.js,引入webpack(5版本)模块联邦,配置插件,同webpack配置一样。
注意:vue-cli目前vue3版本的webpack版本默认是5以下的,需要改下版本。
"@vue/cli-plugin-babel": "~5.0.0-rc.3",
"@vue/cli-plugin-eslint": "~5.0.0-rc.3",
"@vue/cli-plugin-router": "~5.0.0-rc.3",
"@vue/cli-plugin-typescript": "~5.0.0-rc.3",
"@vue/cli-service": "~5.0.0",
小tips: 可以通过命令行 vue config edit 找到.vuerc文件,修改版本,一劳永逸。
{
"useTaobaoRegistry": false,
"packageManager": "pnpm",
"latestVersion": "5.0.4",
"lastChecked": 1648869262012,
"presets": {
"lh": {
"useConfigFiles": true,
"plugins": {
"@vue/cli-plugin-babel": {
"version": "~5.0.0-rc.3"
},
"@vue/cli-plugin-typescript": {
"version": "~5.0.0-rc.3",
"classComponent": true,
"useTsWithBabel": true
},
"@vue/cli-plugin-router": {
"version": "~5.0.0-rc.3",
"historyMode": true
},
"@vue/cli-plugin-eslint": {
"version": "~5.0.0-rc.3",
"config": "prettier",
"lintOn": [
"save"
]
}
},
"vueVersion": "3",
"cssPreprocessor": "less"
}
}
}