# 二.SingleSpa实战

# 1.构建子应用

vue create spa-vue
npm install single-spa-vue 或 yarn add single-spa-vue
1
2
import singleSpaVue from 'single-spa-vue';
const appOptions = {
   el: '#vue',
   router,
   render: h => h(App)
}

// 在非子应用中正常挂载应用
if(!window.singleSpaNavigate){
 delete appOptions.el;
 new Vue(appOptions).$mount('#app');
}

const vueLifeCycle = singleSpaVue({
   Vue,
   appOptions
});

// 子应用必须导出 以下生命周期 bootstrap、mount、unmount
export const bootstrap = vueLifeCycle.bootstrap;
export const mount = vueLifeCycle.mount;
export const unmount = vueLifeCycle.unmount;
export default vueLifeCycle;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const router = new VueRouter({
  mode: 'history',
  base: '/vue',
  routes
})
1
2
3
4
5

配置子路由基础路径

# 2.配置库打包

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

将子模块打包成类库

# 3.主应用搭建

安装

npm i single-spa或 yarn add single-spa
1

挂载子应用

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

将子应用挂载到id="vue"标签中

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);

const loadScript = async (url)=> {
  await new Promise((resolve,reject)=>{
    const script = document.createElement('script');
    script.src = url;
    script.onload = resolve;
    script.onerror = reject;
    document.head.appendChild(script)
  });
}
import { registerApplication, start } from 'single-spa';

registerApplication(
    'singleVue',
    async ()=>{
        await loadScript('http://localhost:10000/js/chunk-vendors.js');
        await loadScript('http://localhost:10000/js/app.js');
        return window.singleVue
    },
    location => location.pathname.startsWith('/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

# 4.动态设置子应用publicPath

if(window.singleSpaNavigate){
  __webpack_public_path__ = 'http://localhost:10000/'
}
1
2
3

# 5.总结

  • 1.微前端分为两种, 一种是组件的微前端, 另一种是路由的微前端
  • 2.子应用需要导出3个方法(bootstrap, mount, unmount)
  • 3.在父应用路径匹配子应用时, 会调用子应用中的方法
  • 4.子应用会挂载到父应用中的标签中, 如果是父应用引用我, 需要修改public_path
  • 5.如果子应用需要独立运行, 需要挂载到vue上
  • 6.但sing-spa还存在一些问题, 比如: 不够灵活,, 不能动态加载js文件, 样式不隔离, 没有js沙箱的机制.......
  • 7.所以, 下面重点介绍 qiankun(乾坤)的使用
上次更新: 2021/1/6 上午11:20:04