vue3微前端架构——基于蚂蚁qiankun框架楔⼦
⾸先,⽬前qiankun框架尚不⽀持vite,
微应⽤不能使⽤vite创建,
即使只是⽣产环境加的载微应⽤也不⾏,
因为vite打包代码时,内部的esbuild会tree shake掉与qiankun相关的⽣命周期钩⼦,
主应⽤没影响,使⽤什么创建项⽬都⽆所谓
主应⽤
没啥特殊的,随便⼀个组件⾥留个容器div
<div id="container"></div>
在⼀个⽅法内加载微应⽤
import { loadMicroApp } from 'qiankun';
export default {
setup(){
let create = ()=>{
loadMicroApp({
name: 'vue3',
entry: 'localhost:7105/',
container: '#container',
});
}
return {create};
}
}
通过路由注册微应⽤的⽅式,请⾃⼰看⽂档
微应⽤
配置⽂件:fig.js
const path = require('path');
const { name } = require('./package');
function resolve(dir) {
return path.join(__dirname, dir);
}
const port = 7105;
outputDir: 'dist',
assetsDir: 'static',
filenameHashing: true,
devServer: {
hot: true,
disableHostCheck: true,
port,
overlay: {
warnings: false,
errors: true,
},
headers: {
'Access-Control-Allow-Origin': '*',
},
},
// ⾃定义webpack配置
configureWebpack: {
resolve: {
alias: {
'@': resolve('src'),
},
},
output: {
// 把⼦应⽤打包成 umd 库格式
library: `${name}-[name]`,
libraryTarget: 'umd',
jsonpFunction: `webpackJsonp_${name}`,
},
},
};
router.js
import HelloWorld from "./components/HelloWorld.vue";
import HelloWorld2 from "./components/HelloWorld2.vue";
import { createRouter, createWebHistory } from "vue-router";
const routes = [
{ path: "/", component: HelloWorld },
{ path: "/about", component: HelloWorld2 },
];
const router = createRouter({
history: createWebHistory(window.__POWERED_BY_QIANKUN__ ? "/vue3" : "/"),
routes,
});
export default router;
main.js
这⾥有好多钩⼦,是给主应⽤⽤的
if (window.__POWERED_BY_QIANKUN__) {
// eslint-disable-next-line no-undef
__webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__; }
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
let instance = null;
function render(props = {}) {
const { container } = props;
instance = createApp(App);
instance.use(router);
}
if (!window.__POWERED_BY_QIANKUN__) {
render();
}
export async function bootstrap() {
console.log("%c ", "color: green;", "vue3.0 app bootstraped");
好用的前端框架}
export async function mount(props) {
render(props);
}
export async function unmount() {
instance.unmount();
instance._container.innerHTML = "";
instance = null;
}
app.vue
<template>
<button @click="go('/')">home</button>
<button @click="go('/about')">sub</button>
<router-view></router-view>
</template>
<script>
import router from "./router"
export default { setup(){
let go = (p)=>{ router.push(p) }
return {go}
}
}
</script>
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论