qiankun 子应用配置

将一个vue2项目修改为子应用,可以在qiankun环境下作为子应用运行,也可以单独运行,具体步骤如下:
1、安装qiankun:

npm i qiankun -S

2、在src下添加public-path.js文件

if (window.__POWERED_BY_QIANKUN__) {
  __webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
}

3、如果出现__webpack_public_path__报错,修改package.json文件,添加以下代码:

"globals": {
      "__webpack_public_path__": true
}

4、修改vue.config.js

const path = require('path');
const { name } = require('./package');

function resolve(dir) {
    return path.join(__dirname, dir);
}

const port = 8981;

module.exports = {
    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}`,
        },
    },
};

5、修改main.js,暴露主应用识别所需的三个必要的生命周期:

// public-path必须第一行就引入
import './public-path'
import Vue from 'vue'
import App from './App.vue'
import axios from 'axios'
import Antd from 'ant-design-vue'
// 原ant-design css
import 'ant-design-vue/dist/antd.css'
// 自定义全局主题样式
import './theam/ant-design-vue.js'
import cryptos from './utils/crypto'
import global_variable from "./utils/global_variable";
// 路由
import routes from './router'
// vuex
import store from './store/index.js'
import Vuex from 'vuex'
import VueRouter from 'vue-router';

Vue.config.productionTip = false;

const instances = axios.create({
  baseURL: '/week'
});

// 配置过滤response
instances.interceptors.response.use((response) => {
  if (response) {
    if (response.data.code === 'FALSE') {
      return 'FALSE';
    }
    return response;
  }
}, error => {
  return Promise.reject(error);
});

// 跨域请求时是否需要使用凭证
instances.defaults.withCredentials = true;

instances.defaults.headers.post['Content-Type'] = 'application/json';
instances.defaults.headers.get['Content-Type'] = 'application/json';

// 配置请求头
instances.defaults.headers.common['x-token'] = sessionStorage.getItem('login');
instances.defaults.headers.common['x-user-id'] = sessionStorage.getItem('userId');

Vue.prototype.$axios = instances;
Vue.use(Antd);
Vue.prototype.cryptos = cryptos;
Vue.prototype.BASEURL = global_variable.baseURL;
Vue.use(Vuex);

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

Vue.config.productionTip = false;

let router = null;
let instance = null;
function render(props = {}) {
  const { container } = props;
  router = new VueRouter({
    base: window.__POWERED_BY_QIANKUN__ ? `${props.name}` : '/',
    mode: 'history',
    routes
  });
  instance = new Vue({
    router,
    store,
    render: h => h(App),
  }).$mount(container ? container.querySelector('#app') : '#app');
}

// webpack打包公共文件路径
if (!window.__POWERED_BY_QIANKUN__) {
  render();
}
// 生命周期
export async function bootstrap(props) {
  const { foo, user } = props;
  sessionStorage.setItem('userInfo',JSON.stringify({foo, user}));
  console.log('[vue] vue app bootstraped');
}
export async function mount(props) {
  console.log('[vue] props from main framework', props);
  render(props);
}
export async function unmount() {
  instance.$destroy();
  instance.$el.innerHTML = '';
  instance = null;
  router = null;
}

6、修改路由:import Vue from ‘vue’

import Router from 'vue-router'

Vue.use(Router);


let routes = [{
    path: "/",
    name: "main", // 首页代码
    component: () => import("../components/main/MainComponent.vue"),
    meta: { breadcrumbName: '首页' },
},{
    path: "/main",
    name: "main", // 测试代码
    component: () => import("../components/navigation/Navigation.vue"),
    meta: { breadcrumbName: '测试' },
},{
    path: "/mainComponent",
    name: "mainComponent", // 首页代码
    component: () => import("../components/main/MainComponent.vue"),
    meta: { breadcrumbName: '登录' },
},{
    path: "/login",
    name: "loginComponent", // 首页代码
    component: () => import("../components/login/LoginComponent.vue"),
    meta: { breadcrumbName: '登录' },
}
];

if (!window.__POWERED_BY_QIANKUN__) {
    // 独立环境
    routes = [
        {
            path: '/',
            redirect: '/mainComponent',
            meta: { title: '首页' }
        },
        {
            path: '/main',
            component: () => import('../components/navigation/Navigation.vue'),
            meta: { title: '侧边栏仪表板' },
            children: [
                {
                    path: '/mainComponent',
                    component: () => import('../components/main/MainComponent.vue'),
                    meta: { title: '主页面' }
                },
                {
                    path: '/test',
                    component: () => import('../components/test/TestComponent.vue'),
                    meta: { title: '测试页面' }
                },
            ]
        },
        {
            path: '/login',
            component: () => import('../components/login/LoginComponent.vue'),
            meta: { title: '登录页' }
        },
        {
            path: '*',
            redirect: '/404'
        }
    ]
}

export default routes;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值