使用vite-plugin-qiankun插件, 将应用快速接入乾坤(vue3 vite)
微前端qiankun使用vite-plugin-qiankun接入Vite子应用(vue3 vite)
·
qiankun官网
vite-plugin-qiankun插件github地址:vite-plugin-qiankun
主应用
1、安装乾坤
$ yarn add qiankun # 或者 npm i qiankun -S
2、在主应用中注册微应用(main.ts)
import { registerMicroApps, start } from 'qiankun';
registerMicroApps([
{
name: 'react app', // app name registered
entry: '//localhost:7100',
container: '#vue-app-container',
activeRule: '/yourActiveRule',
},
{
name: 'vue app',
entry: { scripts: ['//localhost:7100/main.js'] },
container: '#vue-app-container',
activeRule: '/yourActiveRule2',
},
]);
start();
3、挂载
在App.vue挂载微应用节点
<div id="vue-app-container" />
子应用
1、安装插件
qiankun目前是不支持vite的,需要借助插件完成
npm install vite-plugin-qiankun
2、修改vite.config.ts
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import qiankun from 'vite-plugin-qiankun'
// useDevMode 开启时与热更新插件冲突
const useDevMode = true // 如果是在主应用中加载子应用vite,必须打开这个,否则vite加载不成功, 单独运行没影响
export default defineConfig(({ mode }) => {
const root = process.cwd() // process.cwd()返回当前工作目录
const env = loadEnv(mode, root)
let config = {
base: env.VITE_BASE_API,
plugins: [
vue(),
qiankun('vue-app', { // 微应用名字,与主应用注册的微应用名字保持一致
{ useDevMode }
})
],
resolve: {
alias: {
'@': _resolve('src')
}
},
server: {
host: 'x.x.x.x', // 暴露内网ip
port: 8000,
cors: true,
origin: mode === 'development' ? env.VITE_ORIGIN_DEV : env.VITE_BASE_API
},
output: {
// 把子应用打包成 umd 库格式
library: `${子应用名}-[name]`,
libraryTarget: 'umd',
jsonpFunction: `webpackJsonp_${子应用名}`
},
}
return config
})
3、修改main.ts
import { createApp } from 'vue'
import App from './App.vue'
import { createRouter, createWebHashHistory } from 'vue-router'
import {
renderWithQiankun,
qiankunWindow
} from 'vite-plugin-qiankun/dist/helper'
let router = null
let instance = null
let history = null
instance = createApp(App)
declare global {
interface Window {
__POWERED_BY_QIANKUN__: any
__INJECTED_PUBLIC_PATH_BY_QIANKUN__: any
}
}
function render(props = {}) {
const { container } = props as any
history = createWebHashHistory(
qiankunWindow.__POWERED_BY_QIANKUN__ ? '/calendar-mobile' : '/'
)
router = createRouter({
history,
routes
})
instance.use(router)
// instance.use(store);
instance.mount(
container ? container.querySelector('#app') : document.getElementById('app')
)
if (qiankunWindow.__POWERED_BY_QIANKUN__) {
console.log('我正在作为子应用运行')
}
}
// some code
renderWithQiankun({
mount(props) {
console.log('viteapp mount')
render(props)
},
bootstrap() {
console.log('bootstrap')
},
unmount(props) {
console.log('vite被卸载了')
instance.unmount()
instance._container.innerHTML = ''
history.destroy() // 不卸载 router 会导致其他应用路由失败
router = null
instance = null
}
})
if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
render({})
}
更多推荐
已为社区贡献1条内容
所有评论(0)