qiankun 是一个基于 single-spa 的微前端实现库,旨在帮助大家能更简单、无痛的构建一个生产可用微前端架构系统。
qiankun 孵化自蚂蚁金融科技基于微前端架构的云产品统一接入平台,在经过一批线上应用的充分检验及打磨后,我们将其微前端内核抽取出来并开源,希望能同时帮助社区有类似需求的系统更方便的构建自己的微前端系统,同时也希望通过社区的帮助将 qiankun 打磨的更加成熟完善。
目前 qiankun 已在蚂蚁内部服务了超过 200+ 线上应用,在易用性及完备性上,绝对是值得信赖的。
微前端架构具备以下几个核心价值:
主框架不限制接入应用的技术栈,微应用具备完全自主权
微应用仓库独立,前后端可独立开发,部署完成后主框架自动完成同步更新
在面对各种复杂场景时,我们通常很难对一个已经存在的系统做全量的技术栈升级或重构,而微前端是一种非常好的实施渐进式重构的手段和策略
每个微应用之间状态隔离,运行时状态不共享
微前端架构旨在解决单体应用在一个相对长的时间跨度下,由于参与的人员、团队的增多、变迁,从一个普通应用演变成一个巨石应用(Frontend Monolith)后,随之而来的应用不可维护的问题。这类问题在企业级 Web 应用中尤其常见。
用vue-cli创建个项目做基座。
直接用npx安装 npx可拉取最新的命令 @vue/cli去安装 而不用把cli放在本地
1、npx @vue/cli qiankun-base
2、创建初始模板项目(需要路由)
3、安装qiankun库: yarn add qiankun
4、修改main.js
main主要是使用 registerMicroApps, start 方法,配置加载的微项目,按格式配置。
import router from './router';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.config.productionTip = false;
import {
registerMicroApps, start } from 'qiankun';
const apps = [
{
name: 'vueApp',
entry: '//localhost:10002', // 默认会加载这个html 加载里面js 动态执行 必须支持跨域
container: '#vue', // 容器名
activeRule: '/vue', // 激活路由
},
{
name: 'reactApp',
entry: '//localhost:20000', // 默认会加载这个html 加载里面js 动态执行 必须支持跨域
container: '#react',
activeRule: '/react',
},
];
registerMicroApps(apps);
start({
prefetch: false // 取消预加载
});
Vue.use(ElementUI);
new Vue({
router,
render: h => h(App),
}).$mount('#app');
5.修改App.vue
设置好微项目的插座, 用于加载对应dom显示微项目
<template>
<div>
<el-menu :router="true" mode="horizontal">
<!-- 基座自己的路由 -->
<el-menu-item index="/">Home</el-menu-item>
<el-menu-item index="/vue">vue应用</el-menu-item>
<el-menu-item index="/react">react应用</el-menu-item>
</el-menu>
<!-- 默认路由 -->
<router-view></router-view>
<!-- 子应用插槽 -->
<div id="vue"></div>
<div id="react"></div>
</div>
</template>
<script>
export default {
name: 'App',
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
6、router.js正常使用就行
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
1、npx @vue/cli qiankun-vue
2、创建初始模板项目(需要路由)
3、修改main.js
重点是要导出 bootstrap mount unmount 方法,父项目需要调用的
window.POWERED_BY_QIANKUN 用于做判断是否运行在qiankun
/*
* @description:
* @author: steve.deng
* @Date: 2020-08-17 17:52:32
* @LastEditors: steve.deng
* @LastEditTime: 2020-08-18 10:51:32
*/
import Vue from 'vue'
import App from './App.vue'
import router from './router'
/* eslint-disable */
Vue.config.productionTip = false
let instance = null
function render (props) {
instance = new Vue({
router,
render: h => h(App)
}).$mount('#app') // 这里是挂载在自己的html中, 基座会拿到这个挂载后的html 将其插入
}
if (window.__POWERED_BY_QIANKUN__) {
// 动态添加public path
// webpack的路径被赋值
__webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
}
if (!window.__POWERED_BY_QIANKUN__) {
render()
}
// 子组件协议就ok
export async function bootstrap (props) {
}
export async function mount (props) {
render(props)
}
export async function unmount (props) {
instance.$destroy()
}
4、修改router/index.js
主要是base要为 ‘/vue’
/*
* @description:
* @author: steve.deng
* @Date: 2020-08-17 17:52:32
* @LastEditors: steve.deng
* @LastEditTime: 2020-08-18 10:31:46
*/
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
}
]
const router = new VueRouter({
mode: 'history',
base: '/vue', // 配合父级的activeRule 配置使用
routes
})
export default router
5、关键一步
根目录下新建vue.config.js
module.exports = {
devServer: {
port: 10000,
headers: {
'Access-Control-Allow-Origin': '*' // 必须要可跨域访问
}
},
configureWebpack: {
output: {
library: 'vueApp', // 和父项目的配置name相对称
libraryTarget: 'umd'
}
}
}
1、安装react 项目: npx create-react-app qiankun-react
2、安装路由 yarn add react-router-dom
3、安装rewired 用来修改react项目的配置 yarn add react-app-rewired
4、同理,修改index.js 导出固定的三个方法
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
// import * as serviceWorker from './serviceWorker';
function render() {
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
}
// if (window.__POWERED_BY_QIANKUN__) { // 动态添加public path
// // webpack的路径被赋值
// // eslint-disable-next-line no-undef
// __webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
// }
if (!window.__POWERED_BY_QIANKUN__) {
render()
}
// 子组件协议就ok
export async function bootstrap (props) {
console.log('react app bootstraped', props);
}
export async function mount (props) {
console.log('react app mount', props);
render();
}
export async function unmount (props) {
console.log('react app unmount', props);
ReactDOM.unmountComponentAtNode(document.getElementById('root'));
}
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
// serviceWorker.unregister();
5.修改app.js方法
定义路由和渲染组件
/*
* @description:
* @author: steve.deng
* @Date: 2020-08-17 17:01:47
* @LastEditors: steve.deng
* @LastEditTime: 2020-08-18 11:24:44
*/
import React from 'react';
import logo from './logo.svg';
import './App.css';
import {
BrowserRouter, Route, Link} from 'react-router-dom';
function App() {
return (
<BrowserRouter basename="/react">
<Link to="/">首页</Link>
<Link to="/about">关于页面</Link>
<Route path="/" exact render={
() => (
<div className="App">
<header className="App-header">
<img src={
logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
)}
>
</Route>
<Route path="/about" exact render={
() => (
<h1 className="App">
about页面
</h1>
)}
>
</Route>
</BrowserRouter>
);
}
export default App;
6、根目录下新建config-overrides.js
module.exports = {
webpack: (config) => {
config.output.library = 'reactApp'
config.output.libraryTarget = 'umd'
config.output.publicPath = 'http://localhost:20000/'
return config
},
devServer: (configFunction) => {
return function (proxy, allowedHost) {
const config = configFunction(proxy, allowedHost)
config.headers = {
'Access-Control-Allow-Origin': '*'
}
return config;
}
}
}
根目录下新建.env文件
PORT=20000
WDS_SOCKET_PORT=20000
修改package.json的script命令
react-scripts 改为 react-app-rewired
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-app-rewired eject"
},
大致创建好了
微前端初步使用就大概这样,喜欢的点个赞。后续再更新!