lynnes_test_micro_web
v1.0.2
Published
这是一个实验的微前端框架
Readme
micro-web
一个实验的微前端框架
使用方法
主应用
1 在基座应用中使用registerMicroApps注册子应用列表和主应用生命周期
const subNavList = [
{
name: 'subApp',// 唯一标识,子应用名称
entry: '//url/', // 入口路径
container: '#micro-container', // 渲染容器
activeRule: '/index', // 子应用的根路由,激活的路由
appInfo, // 主子应用传值
},
]
registerMicroApps(subNavList, {
beforeLoad: [
() => {
loading.changeLoading(true)
console.log('开始加载')
}
],
mounted: [
() => {
loading.changeLoading(false)
console.log('渲染完成')
}
],
destoryed: [
() => {
console.log('卸载完成')
}
]
})2 使用start()方法启动
子应用配置
1 webpack配置
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'react15.js',
library: 'react15',
libraryTarget: 'umd',
umdNamedDefine: true,
publicPath: 'http://localhost:9002/'
},
devServer: {
// 配置允许跨域
headers: { 'Access-Control-Allow-Origin': '*' },
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 9002,
historyApiFallback: true,
hot: true,
}2 入口文件配置
- 将挂载应用作为一个方法放在mount生命周期中去执行
- 将生命周期暴露出去
import Vue from 'vue'
import App from './App.vue'
import router from './router'
Vue.config.productionTip = false
const render = () => {
new Vue({
router,
render: h => h(App)
}).$mount('#app-vue')
}
if (!window.__MICRO_WEB__) {
render()
}
export async function bootstrap() {
console.log('bootstrap');
}
export async function mount() {
render()
}
export async function unmount(ctx) {
const { container } = ctx
if (container) {
document.querySelector(container).innerHTML = ''
}
}
可选的额外功能
全局状态管理库
1 使用createStore创建全局状态管理库
2 使用window.custom事件总线的方式进行应用间的通信
3 使用prefetch预加载子应用
关于微前端应用调试
可以通过执行这个脚本同时启动主子应用进行调试,注意根据自己的项目情况进行修改替换
const childProcess = require('child_process')
const path = require('path')
const filePath = {
vue2: path.join(__dirname, '../vue2'),
vue3: path.join(__dirname, '../vue3'),
react15: path.join(__dirname, '../react15'),
react16: path.join(__dirname, '../react16'),
main: path.join(__dirname, '../main')
}
// cd 子应用的目录 npm start 启动项目
function runChild () {
Object.values(filePath).forEach(item => {
childProcess.spawn(`cd ${item} && npm start`, { stdio: "inherit", shell: true })
})
}
runChild()
