-
背景
客户需求是使用前端使用图将项目流程进行可视化,为了方便后期维护,将此功能独起一个项目,之后嵌入到主应用中。
技术选型:
- 主应用:vite+vue3
- 子应用:vite+vue3+butterfly-dag
- 微前端:qiankun
注意事项:
- 乾坤使用了vite-plugin-qiankun插件
- 本文为本地开发环境配置
-
主应用和子应用配置
主应用
在main.js文件中
// 主应用的入口文件
import { registerMicroApps, setDefaultMountApp,start } from 'qiankun';
registerMicroApps([
{
name: 'vue-project', // 子应用名称,必须唯一 ,须与子应用中package.json中的name属性相同
entry: 'http://xxx:port', // 子应用的地址
container: '#butterfly-dag', // 页面中挂载子应用的元素节点
activeRule: '/test', // 触发子应用加载的页面url,需要在子应用路由中
},
]);
start(); // 运行乾坤
子应用
在main.js文件中
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import { renderWithQiankun, qiankunWindow } from 'vite-plugin-qiankun/dist/helper';
import App from './App.vue'
import router from './router'
const app = createApp(App)
renderWithQiankun({
mount(props) {
console.log("before props")
render(props);
console.log("after props")
},
bootstrap() {
console.log("%c ", "color: green;", "app bootstraped");
},
unmount(props) {
app.unmount();
},
});
function render(props) {
const { container } = props;
app.use(createPinia())
app.use(router)
app.mount(container ? container.querySelector('#app') : '#app')
}
// 独立运行时
if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
render({});
}
在vite.config.js文件中
import qiankun from "vite-plugin-qiankun";
export default defineConfig({
base: 'http://xxx:port', //主应用的地址
plugins: [
vue(),
qiankun('vue-project', { //子应用name,须与子应用中package.json中的name属性相同
useDevMode: true
})
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
})
在路由文件中,index.js
routes: [
{
path: '/test',//注意点:需要与主应用main.js文件中的activeRule属性相同
name: 'home',
component: () => import('../views/Home.vue')
},
]