qiankun+vue微前端實戰配置流程詳解,包含基座配置、子應用配置、引數傳遞
阿新 • • 發佈:2021-10-13
qiankun 整合指引文件
qiankun 是一個生產可用的微前端框架,它基於 single-spa,具備 js 沙箱、樣式隔離、HTML Loader、預載入 等微前端系統所需的能力。qiankun 可以用於任意 js 框架,微應用接入像嵌入一個 iframe 系統一樣簡單。
一、qiankun 網址
https://qiankun.umijs.org/zh
二、安裝 qiankun 依賴
$ npm i qiankun -S
三、基座
1、路由模式:history 路由(/router/index.ts)
const router = createRouter({ // history模式 history: createWebHistory(process.env.BASE_URL), routes, })
2、 註冊子應用,開啟服務(main.ts)
import { registerMicroApps, start } from 'qiankun' // 註冊子應用 registerMicroApps([ { name: 'usercenter', // 子應用名稱 entry: 'http://localhost:8088', // 子應用地址,開發環境和生產環境值不同,需動態配置 container: '#usercenter', // 子應用容器 activeRule: '/usercenter', // 子應用觸發規則(路徑) }, ]) // 開啟服務 start()
3、新增子應用容器(App.vue)
<div id="usercenter"></div>
4、新增子應用的服務代理,基座需配置子應用的服務(vue.config.js)
devServer: { port: 8033, // 埠號 host: '0.0.0.0', disableHostCheck: true, headers: { 'Access-Control-Allow-Origin': '*' }, proxy: { '/api': {// 子應用1服務 target: process.env.VUE_APP_API_URL, changeOrigin: true, pathRewrite: { '^/api': '' } }, '/spider': {// 子應用2服務 target: process.env.VUE_APP_API_URL_SPIDER, changeOrigin: true, pathRewrite: { '^/spider': '' } } } }
四、子應用
1、路由模式:history 路由(/router/index.ts)
const router = createRouter({
// history模式
history: createWebHistory('/usercenter'),// 字首需要和基座main.ts裡面配置的啟用路由一致
routes,
})
2、向基座暴露介面,使基座與子應用互通(main.ts)
const temp: any = window
const isQiankun = temp.__POWERED_BY_QIANKUN__
if (isQiankun) {
__webpack_public_path__ = temp.__INJECTED_PUBLIC_PATH_BY_QIANKUN__
}
function render(props?: any) {
......
}
export async function mount(props: any) {
render(props)
}
export async function unmount(props: any) {
console.log(props)
}
export async function update(props: any) {
console.log('update props', props)
}
isQiankun || render()
3、修改子應用打包格式(vue.config.js)
const { name } = require('./package')
const port = 8088
const dev = process.env.NODE_ENV === 'development'
module.exports = {
// 配置publicPath,填寫你本機的ip地址
publicPath: dev ? `//192.168.xx.xx:${port}` : process.env.BASE_URL,
// 自定義webpack配置
configureWebpack: {
output: {
// 把子應用打包成 umd 庫格式
library: `${name}-[name]`,
libraryTarget: 'umd',
jsonpFunction: `webpackJsonp_${name}`,
},
},
devServer: {
port, // 埠號
host: '0.0.0.0',
disableHostCheck: true,
// 子應用需要支援跨域
headers: {
'Access-Control-Allow-Origin': '*',
},
// history模式下的url會請求到伺服器端,但是伺服器端並沒有這一個資原始檔,就會返回404,所以需要配置這一項
historyApiFallback: {
index: '/index.html',
},
},
}
五、主子應用間建立通訊
1、基座
① 通訊檔案(src/actions.ts)
import { initGlobalState, MicroAppStateActions } from 'qiankun'
const initialState = {}
const actions: MicroAppStateActions = initGlobalState(initialState)
export default actions
② 向子應用傳送資料資料 示例 ( /login.vue )
// 主應用通訊
import actions from '@/actions'
const token = `${res.tokenType} ${res.token}`
// 登入成功後,設定 token
actions.setGlobalState({ token })
2、子應用
① 通訊檔案(src/actions.ts)
function emptyAction() {
// 警告:提示當前使用的是空 Action
console.warn('Current execute action is empty!')
}
class Actions {
// 預設值為空 Action
actions = {
onGlobalStateChange: emptyAction,
setGlobalState: emptyAction
}
/**
* 設定 actions
*/
setActions(actions) {
this.actions = actions
}
/**
* 對映
*/
onGlobalStateChange(...args: any) {
console.log(...args)
// return this.actions.onGlobalStateChange(...args)
}
/**
* 對映
*/
setGlobalState(...args) {
console.log(...args)
// return this.actions.setGlobalState(...args)
}
}
const actions = new Actions()
export default actions
② 接收基座傳送的資料 示例 ( main.ts )
import actions from '@/actions'
function render(props?: any) {
if (props) {
// 注入 actions 例項
actions.setActions(props)
}
......
}
export async function mount(props: any) {
console.log(props)
// debugger
render(props)
// 註冊觀察者函式 獲取主應用傳遞過來的引數
// onGlobalStateChange 第二個引數為 true,表示立即執行一次觀察者函式
props.onGlobalStateChange((state) => {
const { token } = state
if (token) {
localStorage.setItem('ACCESS_TOKEN', token)
}
}, true)
}
......