個人博客: https://alili.tech/
距離第一篇聊前端微服務(wù)的文章已經(jīng)時隔大半年,很多人對此感興趣.
今天我們就聊一聊,我們?nèi)绾位趗mi來打造一個更完善的前端微服務(wù)的子模塊.
如果你用的是react以外的前端技術(shù)棧,
我的很多處理做法也可以應(yīng)用在其他技術(shù)棧上.
希望對你也有所幫助.
優(yōu)秀的umi框架
在前端中后臺項目上,前端微服務(wù)化的需求相對是比較旺盛一些的.
說到中后臺,很多企業(yè)都是基于antd的組件來構(gòu)建自己的項目.
自去年的see conf
之后,螞蟻的一款可插拔的企業(yè)級 react 應(yīng)用框架
umi發(fā)布了.
這款框架與antd息息相關(guān),antd結(jié)合umi使用那是相當?shù)淖匀慌c流暢.
可以說,基于umi與antd構(gòu)建的項目非常的漂亮.這么優(yōu)秀的框架,如果讓他適用于我們的前端微服務(wù)架構(gòu),豈不美哉?
umi也有相關(guān)的類似微服務(wù)方案: https://github.com/umijs/umi-example-monorepo
但是umi提供的方案,有很大的局限性.
如果可以接入single-spa的微服務(wù)方案,獨立開發(fā),獨立部署等等的前端微服務(wù)化紅利,
會讓你的項目日后有更大的發(fā)展空間.
基于umi插件機制做到前端微服務(wù)化
umi 提供了非常強大的插件機制,正是由于這一點,我們才可以讓umi也可以接入到微服務(wù)架構(gòu)中來
umi插件介紹
umi插件的基本介紹:
umi插件開發(fā)
這里介紹了如何開發(fā)一個簡單的umi插件:
https://umijs.org/zh/plugin/develop.html
接入single-spa的umi插件
export default (api, opts) => {
// 以下的所有代碼都寫在這里面哦
};
渲染入口處理方法
定義一個動態(tài)的元素,當我們的base app 需要加載子模塊的時候,會渲染出子模塊需要渲染元素.
我們的子模塊找到了自己模塊需要渲染的節(jié)點的時候,就會渲染出來.
const domElementGetterStr = `
function domElementGetter() {
let el = document.getElementById('submodule-page')
if (!el) {
el = document.createElement('div')
el.id = 'submodule-page'
}
let timer = null
timer = setInterval(() => {
if (document.querySelector('#submoduleContent.submoduleContent')) {
document.querySelector('#submoduleContent.submoduleContent').appendChild(el)
clearInterval(timer)
timer = null
}
}, 100)
return el
}`
使用single-spa-react
在umi的入口文件導(dǎo)入single-spa-react
,根據(jù)模塊的屬性來判斷模塊在運行時是否渲染在root節(jié)點上還是指定節(jié)點
// 生產(chǎn)環(huán)境使用
if (process.env.NODE_ENV === 'production') {
api.addEntryCodeAhead(`
import singleSpaReact from 'single-spa-react';
let reactLifecycles;
reactLifecycles = singleSpaReact({
React,
ReactDOM,
rootComponent: (customProps) => window.g_plugins.apply('rootContainer', {
initialValue: React.createElement(require('./router').default,customProps),
}),
domElementGetter: ${options.base?`() => document.getElementById('root')`:domElementGetterStr}
});
`);
}
對外導(dǎo)出標準的生命周期
清空umi原來的渲染方法,并且對外導(dǎo)出single-spa需要的生命周期.
// 生產(chǎn)環(huán)境使用
if (process.env.NODE_ENV === 'production') {
api.modifyEntryRender(``)
api.addEntryCode(`
export const bootstrap = [
reactLifecycles.bootstrap,
];
export const mount = [
reactLifecycles.mount,
];
export const unmount = [
reactLifecycles.unmount,
];
`)
}
這樣我們就得到了一個兼容single-spa的umi子模塊.
打包相關(guān)
api.modifyWebpackConfig((config) => {
// 打包的還是amd模塊
config.output.libraryTarget = 'amd'
// 指定模塊名稱
config.output.library = options.name;
//根據(jù)自己部署情況來修改outputPath
config.output.path = resolve(`./dist/${options.deployPath}/`);
// 根據(jù)自己部署情況來修改publicPath
config.output.publicPath = options.deployPath;
return config;
})
}
api.modifyDefaultConfig(memo => ({
// webpack的配置修改,umi也提供了 chainWebpack
...memo,
//指定路由模式
history: 'hash',
// 導(dǎo)出用于通信的store文件
// 如果你不知道這個是用來干什么的,可以讀一讀以前的文章
chainWebpack(config) {
config
.entry('store').add('./src/store.js')
.end()
}
}));
umi的全局變量問題
umi對外提供了很多的全局變量,當我們的微前端架構(gòu)中,只有一個模塊是umi構(gòu)建的話,不需要考慮這個問題,如果有多個模塊使用了umi,將會出現(xiàn)全局變量沖突的問題.還好umi的全局變量是有規(guī)范的,我們可以針對性處理.
我給出以下解決方案,可能相對暴力,但是也能解決沖突的問題.如果你有更好更加優(yōu)雅的辦法,歡迎交流.
大致思路是,在項目打包完成后,把每個文件的全局變量全部替換成其他的名字.
// 打包后替換全局變量以免沖突
api.onBuildSuccess(() => {
const outPath = resolve('.', `dist/${options.deployPath}`);
readdir(outPath, 'utf8', (err, data) => {
data.forEach((item) => {
if (!lstatSync(resolve(outPath, item)).isDirectory()) {
readFile(resolve(outPath, item), 'utf8', (error, files) => {
if (error) {
console.log(error);
return
}
// 替換全局變量
const result = files.replace(/window.g_/g, `window.g_${options.name}_`);
writeFile(resolve(outPath, item), result, 'utf8', (err2) => {
if (err2) console.log(err2);
});
})
}
});
})
})
尾巴
umi的插件機制真的很優(yōu)秀,為了讓umi也可以接入到single-spa的微服務(wù)化的方案中來,基本上umi源碼都看了一遍.真的是受益匪淺~
以上就是讓umi微服務(wù)化的方法,請根據(jù)自身的項目情況修改與使用.
后面我還會介紹一些前端項目微服務(wù)化之后,帶來的很多意想不到的騷操作.
這種基礎(chǔ)技術(shù)的進步,未來可以帶來無法估量的收益與改變.
請關(guān)注后續(xù)的系列文章.