single-spa 微前端部署

什么是微前端

微前端指的是在于浏览器中得微服务。

微前端是用户界面中的一部分,可以分割为多个react、Vue、Angular等框架来渲染组合。没有微前端可由不同的开发团队只管里选择不同框架。比如拥有独立的git仓库、独立构建等。

构建主应用

1、安装single-spa依赖npm install single-spa --save -d并在mian.js中引入

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import './single-spa-config.js'

Vue.config.productionTip = false

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

2、创建single-spa的配置文件为single-spa-config

singleSpa.registerApplication: 注册子应用;
appName: 子应用名称;
applicationOrLoadingFn: 子应用注册函数,子应用需要返回 single-spa 的生命周期对象;
activityFn: 回调函数入参 location 对象,可以写自定义匹配路由加载规则;

/* eslint-disable */
import * as singleSpa from 'single-spa'; //导入single-spa
import axios from 'axios';
/*
* runScript:一个promise同步方法。可以代替创建一个script标签,然后加载服务
* */
const runScript = async (url) => {
    return new Promise((resolve, reject) => {
        const script = document.createElement('script');
        script.src = url;
        script.onload = resolve;
        script.onerror = reject;
        const firstScript = document.getElementsByTagName('script')[0];
        firstScript.parentNode.insertBefore(script, firstScript);
    });
};

/*
* getManifest:远程加载manifest.json 文件,解析需要加载的js
* */
const getManifest = (url, bundle) => new Promise(async (resolve) => {
    console.log(url, bundle)
    const { data } = await axios.get(url);
    const { entrypoints, publicPath } = data;
    const assets = entrypoints[bundle].assets;
    for (let i = 0; i < assets.length; i++) {
        await runScript(publicPath + assets[i]).then(() => {
            if (i === assets.length - 1) {
                resolve()
            }
        })
    }
});
singleSpa.registerApplication( //注册微前端服务
    'cv',
    async () => {
        // 注册用函数,
        // return 一个singleSpa 模块对象,模块对象来自于要加载的js导出
        // 如果这个函数不需要在线引入,只需要本地引入一块加载:
        // () => import('xxx/main.js')
        let singleVue = null;
        await getManifest('http://localhost:3000/manifest.json', 'app').then(() => {
            singleVue = window.singleVue;
        });
        return singleVue;
    },
    location => location.pathname.startsWith('/cv/') // 配置微前端模块前缀
);
singleSpa.registerApplication( //注册微前端服务
    'lb',
    async () => {
        let singleVue = null;
        await getManifest('http://localhost:5000/manifest.json', 'app').then(() => {
            singleVue = window.singleVue;
        });
        return singleVue;
    },
    location => location.pathname.startsWith('/lb/') // 配置微前端模块前缀
);
singleSpa.start(); // 启动

3、在路由中注册统一路由,我们注册一个子服务路由,可填不填写component字段。

{
              path: '/cv',
                name: 'cv',
                component: () => import(/* webpackChunkName: "about" */ '@/components/child.vue')
            },

child.vue文件


App.vue 增加一个 子项目dom 的 id

// 点击路由跳转
lb
// 子项目id


子项目创建

1、安装single-spa-vue依赖npm install single-spa-vue --save -d

在mian.js中引入

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './vuex/store'
import singleSpaVue from 'single-spa-vue'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

Vue.config.productionTip = false
Vue.use(ElementUI);

const errorHandler = (error, vm) => {
    console.error('抛出全局异常', error);
}
Vue.config.errorHandler = errorHandler;
Vue.prototype.$throw = (error) => errorHandler(error, this);

const vueOptions = {
    el: '#childApp',
    router,
    store,
    render: h => h(App)
}

// 判断当前页面使用singleSpa应用,不是就渲染
if (!window.singleSpaNavigate) {
    delete vueOptions.el
    new Vue(vueOptions).$mount('#app')
}

// singleSpaVue包装一个vue微前端服务对象
const vueLifecycles = singleSpaVue({
    Vue,
    appOptions: vueOptions
})

export const bootstrap = vueLifecycles.bootstrap // 启动时
export const mount = vueLifecycles.mount // 挂载时
export const unmount = vueLifecycles.unmount // 卸载时
export default vueLifecycles

2、安装stats-webpack-plugin插件npm install stats-webpack-plugin --save -d

vue.config.js

const StatsPlugin = require('stats-webpack-plugin');
module.exports = {
   publicPath: '//localhost:5000',
    // css在所有环境下,都不单独打包为文件。这样是为了保证最小引入(只引入js)
    css: {
        extract: false
    },
   
    configureWebpack: (config) => {
        if (env === 'production') {
            config.plugins.push(
                new UglifyJsPlugin({
                    uglifyOptions: {
                        compress: {
                            // warnings: false,
                            drop_debugger: true, // console
                            drop_console: true,
                            pure_funcs: ['console.log'] // 移除console
                        }
                    }
                })
            );
        }
        config.plugins.push(
            new StatsPlugin('manifest.json', {
            chunkModules: false,
            entrypoints: true,
            source: false,
            chunks: false,
            modules: false,
            assets: false,
            children: false,
            exclude: [/node_modules/]
        }))
        config.output.library = 'singleVue'
        config.output.libraryTarget = 'window'
    },
        devtool: 'none'
    },
    devServer: {
        contentBase: path.join(__dirname, 'dist'),
        compress: true,
        port: 5000,
        headers: {"Access-Control-Allow-Origin":"*"} //本地跨域处理
    }
}

3、router 配置

const router = new VueRouter({
  mode: 'history',
  base: '/cv/',
  routes
})

你可能感兴趣的:(single-spa 微前端部署)