微应用配置
1.在 src
目录新增 public-path.js,将public-path.js引入到main.js中。
if (window.__POWERED_BY_QIANKUN__) {
__webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
}
2.修改main.js配置,引入qiankun相应生命周期钩子(导出 bootstrap
、mount
、unmount
三个生命周期钩子,以供主应用在适当的时机调用)
main.js代码
import './public-path'
import Vue from 'vue'
import echarts from 'echarts'
import 'normalize.css/normalize.css' // A modern alternative to CSS resets
import routes from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import multiCascader from '@/components/multiCascader/index'
import elTableInfiniteScroll from 'el-table-infinite-scroll'
import '@/styles/index.scss' // global css
import '@/styles/standingBook.scss' // standingBook css
import App from './App'
import store from './store'
import { formatDist, formatToThousands, formatDistFilter } from './utils/util'
import * as filters from '@/utils/util'
Object.keys(filters).forEach(key => {
Vue.filter(key, filters[key])// 插入过滤器名和对应方法
})
Vue.prototype.formatDist = formatDist
Vue.prototype.formatDistFilter = formatDistFilter
Vue.prototype.formatToThousands = formatToThousands
Vue.prototype.$echarts = echarts
// 中文版 element-ui
Vue.use(ElementUI)
Vue.use(multiCascader) // 级联选择器
Vue.config.productionTip = false
Vue.use(elTableInfiniteScroll)
let instance = null;
let router = null
function render(props = {}) {
const { container } = props
router = new VueRouter({
base: window.__POWERED_BY_QIANKUN__ ? '/Test':'/',
mode: 'hash',
routes
})
router.beforeEach((to,from,next)=>{
console.log('beforeEach',to,from);
next()
})
instance = new Vue({
router,
store,
render: h => h(App)
}).$mount(container?container.querySelector('#app'):'#app')
}
// 独立运行时
if (!window.__POWERED_BY_QIANKUN__) {
render();
}
export async function bootstrap() {
console.log('vue子应用bootstrap');
}
export async function mount(props) {
console.log('vue子应用mount', props);
render(props);
}
export async function unmount(props) {
console.log('vue子应用卸载', props);
instance.$destroy();
instance.$el.innerHTML = '';
instance = null;
router = null;
}
3.路由为hash模式时,需要添加路由前缀(页面尽量import引入,component引入可能会有兼容问题)
router.js
import Vue from 'vue'
import Router from 'vue-router'
// import store from '../store'
Vue.use(Router)
/* Layout */
import Layout from '@/layout'
import consumer from'@/views/test/test1'
import roles from'@/views/test/test2'
//qiankun模式下路由添加前缀
let microPath = ''
if (window.__POWERED_BY_QIANKUN__) {
microPath = '/Pledged'
}
export const constantRoutes = [
{
path: microPath+'/test',
component: Layout,
children: [{
path:'test1',
component: test1,
name: 'test1',
},
{
path: 'test2',
name: 'test2',
component: test2,
}]
},
]
const routes = constantRoutes
export default routes
4.修改vue.config.js
'use strict'
const path = require('path')
const _publicPath = '/test/'
const defaultSettings = require('./src/settings.js')
function resolve(dir) {
return path.join(__dirname, dir)
}
const names = defaultSettings.title // page title
const { name } = require('./package');
const port = 3004 // dev port
// 所有配置项的说明: https://cli.vuejs.org/config/
module.exports = {
/**
* 如果您计划在子路径下部署站点,则需要设置publicPath,
* 在大多数情况下请使用'/' !!!
* https://cli.vuejs.org/config/#publicpath
*/
//在test子路径下部署
publicPath: process.env.NODE_ENV === 'production' ? '/test/' : '/'
outputDir: 'dist',
assetsDir: 'static',
transpileDependencies: ['@antv/g6'], // antv.g6
lintOnSave: process.env.NODE_ENV === 'development',
productionSourceMap: false,
devServer: {
port: port,
open: true,
overlay: {
warnings: false,
errors: true
},
// 关闭主机检查,使微应用可以被 fetch
disableHostCheck: true,
headers: {
'Access-Control-Allow-Origin': '*',
},
proxy: {
[process.env.VUE_APP_BASE_API]: {
target: 'http://114.113.127.115:9009/prod-api/', // 阿里云地址
changeOrigin: true,
pathRewrite: {
['^' + process.env.VUE_APP_BASE_API]: ''
}
}
}
},
configureWebpack: {
// 在webpack的name字段中提供应用程序的标题,以便可以在index.html中访问它以插入正确的标题。
name: names,
resolve: {
alias: {
'@': resolve('src')
}
},
output: {
library: 'inside-grade2',
libraryTarget: 'umd', // 把微应用打包成 umd 库格式
jsonpFunction: 'webpackJsonp_inside-grade2',
},
},
chainWebpack(config) {
config.plugins.delete('preload') // TODO: need test
config.plugins.delete('prefetch') // TODO: need test
// set svg-sprite-loader
config.module
.rule('svg')
.exclude.add(resolve('src/icons'))
.end()
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(resolve('src/icons'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]'
})
.end()
//修改elementUI icon部署后不显示的问题
config.module
.rule('fonts')
.use('url-loader')
.loader('url-loader')
.tap(options => {
options['limit'] = 4096
options['publicPath'] = _publicPath //添加路径
return options;
})
// set preserveWhitespace
config.module
.rule('vue')
.use('vue-loader')
.loader('vue-loader')
.tap(options => {
options.compilerOptions.preserveWhitespace = true
return options
})
.end()
config
// https://webpack.js.org/configuration/devtool/#development
.when(process.env.NODE_ENV === 'development',
config => config.devtool('cheap-source-map')
)
config
.when(process.env.NODE_ENV !== 'development',
config => {
config
.plugin('ScriptExtHtmlWebpackPlugin')
.after('html')
.use('script-ext-html-webpack-plugin', [{
// `runtime` must same as runtimeChunk name. default is `runtime`
inline: /runtime\..*\.js$/
}])
.end()
config
.optimization.splitChunks({
chunks: 'all',
cacheGroups: {
libs: {
name: 'chunk-libs',
test: /[\\/]node_modules[\\/]/,
priority: 10,
chunks: 'initial' // only package third parties that are initially dependent
},
elementUI: {
name: 'chunk-elementUI', // split elementUI into a single package
priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
},
commons: {
name: 'chunk-commons',
test: resolve('src/components'), // can customize your rules
minChunks: 3, // minimum common number
priority: 5,
reuseExistingChunk: true
}
}
})
config.optimization.runtimeChunk('single')
}
)
}
}