Skip to content
On this page

singleSpa

将子模块打包成类库 -> 在父应用中直接调用

优点

  • 自由度高,可以通过 js 做到预加载,有基座应用做把控,体验更完善,并且同一页面可以存在多个子应用

缺点

  • 不够灵活 不能动态加载 js 文件

  • 样式不隔离 没有 js 沙箱的机制

构建子应用

bash
vue create child-vue
npm install single-spa-vue
1
2

配置基本设置

javascript
// child-vue main.js
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import singleSpaVue from "single-spa-vue";

Vue.config.productionTip = false;

const appOptions = {
  el: "#vue", // 挂载到父应用的标签中
  router,
  render: h => h(App)
};

// 1. 需要加载父项目加载子应用
// bootstrap mount unmount
const vueLifeCycle = singleSpaVue({
  Vue,
  appOptions
});

if (window.singleSpaNavigate) {
  __webpack_public_path__ = "http://localhost:8081/";
}

if (!window.singleSpaNavigate) {
  delete appOptions.el;
  new Vue(appOptions).$mount("#app");
}

// 2.协议接入 我定义好了协议 父应用会调用这些函数
export const bootstrap = vueLifeCycle.bootstrap;
export const mount = vueLifeCycle.mount;
export const unmount = vueLifeCycle.unmount;
export default vueLifeCycle;
// 3.将子应用打包成lib去给父应用使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

配置路由

javascript
const router = new VueRouter({
  mode: 'history',
  base: '/vue',
  routes
})
1
2
3
4
5

配置库打包

javascript
module.exports = {
  configureWebpack: {
    output: {
      library: "singleVue",
      libraryTarget: "umd"
    },
    devServer: {
      port: 8081
    }
  }
};
1
2
3
4
5
6
7
8
9
10
11

主应用搭建

bash
vue create parent-vue
1
html
<div id="nav">
    <router-link to="/vue">vue项目</router-link>
    <div id="vue"></div>
</div>
1
2
3
4

main.js

javascript

import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import { registerApplication, start } from "single-spa";
Vue.config.productionTip = false;

async function loadScript(url) {
  return new Promise((resolve, reject) => {
    let script = document.createElement("script");
    script.src = url;
    script.onload = resolve;
    script.onerror = reject;
    document.head.appendChild(script);
  });
}

// singleSpa 缺陷 不够灵活 不能动态加载js文件
// 样式不隔离 没有js沙箱的机制

registerApplication(
  "myVueapp",
  async () => {
    console.log("加载模块");
    await loadScript(`http://localhost:8081/js/chunk-vendors.js`);
    await loadScript(`http://localhost:8081/js/app.js`);
    return window.singleVue;
  },
  location => location.pathname.startsWith("/vue")
); //用户切换到/vue的路径下,我需要加载刚才定义的子应用

start();

new Vue({
  router,
  render: h => h(App)
}).$mount("#app");
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
沪ICP备20006251号-1