qiankun官方是不支持vite项目的,通过搜索和测试发现vite-plugin-qiankun这个插件可以支持vite项目接入子应用
GitHub地址 https://github.com/tengmaoqing/vite-plugin-qiankun
代码里example中有vue和react的具体用法
我这里简单记录一下vite构建的vue3作为子项目的用法:
1.安装vite-plugin-qiankun
npm i vite-plugin-qiankun
2.修改router模式改为history模式,主应用也需要是history模式
router的index文件中
import { createRouter, createWebHistory } from 'vue-router';
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper';
const router = createRouter({
// 判断是否在qiankun环境里,xxx与主应用中activeRule一致
history: createWebHistory(qiankunWindow.__POWERED_BY_QIANKUN__ ? '/xxx' : '/'),
routes: routes,
...
});
3.修改main.js
import { createApp } from 'vue';
import mitt from 'mitt';
import { renderWithQiankun, qiankunWindow } from 'vite-plugin-qiankun/dist/helper';
...
const app = createApp(App);
// 挂载函数
function render(props:any) {
const { container } = props;
app.use(router);
app.mount(container ? container.querySelector('#indexContainer') : '#indexContainer'); // 这个ID为index.html中div的ID名称
app.config.globalProperties.mittBus = mitt();
}
renderWithQiankun({
mount(props) {
console.log(, props);
render(props);
// store.commit("updateUserInfo",props);
// 在vue全局注册主应用的状态监听和状态改变事件
app.config.globalProperties.$onGlobalStateChange = props.onGlobalStateChange;
app.config.globalProperties.$setGlobalState = props.setGlobalState;
},
bootstrap() {
console.log('bootstrap');
},
unmount() {
console.log('unmount');
app.unmount();
},
update() {
console.log('update');
},
});
if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
render({});
}
4.vite.config.ts配置修改
import qiankun from 'vite-plugin-qiankun';
const useDevMode = true; // useDevMode = true 时不开启热更新
...
export const viteConfig = defineConfig(({ command, mode }) => ({
// 这一步是为在主应用访问子应用时,配置写死子应用的静态资源地址,不加这个配置项目单独运行没有问题,但在微前端环境下跳转时因访问资源地址不对会报错
base: mode === 'development' ? './' : '子项目的访问地址',
plugins: [
vue(),
...
qiankun('AAA', { useDevMode }), // AAA中是子应用名,主应用注册时AppName需保持一致
],
...
// 开发服务器配置
server: {
...
origin: 'http://localhost:8500', //项目baseUrl,解决主应用中出现静态地址404问题
},
}));