SingleSpa - VueCli - 微前端落地方案
- 創(chuàng)建項(xiàng)目parent-vue和child-vue兩個(gè)項(xiàng)目
- vue create parent-vue
- vue create child-vue
parent-Vue
安裝依賴(lài): yarn add
yarn add single-spa
-
main.js改造
import Vue from "vue"; import App from "./App.vue"; import router from "./router"; import store from "./store"; Vue.config.productionTip = false; import './single-spa'; new Vue({ router, store, render: (h) => h(App), }).$mount("#app");
// single-spa.js import { registerApplication, start } from "single-spa"; async function loadScript(url) { return new Promise((resolve, reject) => { // 創(chuàng)建標(biāo)簽,并將標(biāo)簽加到head中 let script = document.createElement("script"); script.src = url; script.onload = resolve; script.onerror = reject; document.head.appendChild(script); }); } // 注冊(cè)應(yīng)用 registerApplication( "myVueApp", async () => { // 加載子組件導(dǎo)出的類(lèi)庫(kù)和資源,注意先后順序 await loadScript(`http://localhost:3001/js/chunk-vendors.js`); await loadScript(`http://localhost:3001/js/app.js`); return window.singleVue; // 返回子應(yīng)用里導(dǎo)出的生命周期,mount,ummount,bootstrap }, // 當(dāng)用戶(hù)切換到/myVueApp的路徑下時(shí)嫌吠,加載剛才定義子子應(yīng)用 (location) => location.pathname.startsWith("/myVueApp") ); start();
child-Vue
安裝依賴(lài): yarn add single-spa-vue
-
vue.config.js調(diào)整
module.exports = { publicPath: "http://localhost:3001/", // css在所有環(huán)境下抢韭,都不單獨(dú)打包為文件。這樣是為了保證最小引入(只引入js) css: { extract: false }, // chainWebpack: config => { // config.externals(['vue', 'vue-router']); // }, configureWebpack: { output: { library: "singleVue", //掛載目標(biāo) umd or window libraryTarget: "umd", }, devServer: { contentBase: './', compress: true, port: 3001, }, }, };
-
main.js改造
import Vue from "vue"; import App from "./App.vue"; import router from "./router"; import store from "./store"; import singleSpaVue from 'single-spa-vue'; Vue.config.productionTip = false; const appOptions = { el: '#child-vue', // 掛載到父應(yīng)用中id為vue的標(biāo)簽中 router, store, render: h => h(App) } // 使用 singleSpaVue 包裝 Vue, // 包裝后返回的對(duì)象中vue包裝好的三個(gè)生命周期,bootstrap,mount,unmount, const vueLifeCycle = singleSpaVue({ Vue, appOptions }); // 協(xié)議接入,我們定好了協(xié)議,父應(yīng)用會(huì)調(diào)用這些方法 export const bootstrap = vueLifeCycle.bootstrap; export const mount = vueLifeCycle.mount; export const unmount = vueLifeCycle.unmount; /* new Vue({ router, store, render: (h) => h(App), }).$mount("#app"); */