zh-hans.single-spa.js.org/javascript
single-spa:https://single-spa.js.org/ 是一個實現微前端架構的框架。html
在 single-spa 框架中有三種類型的微前端應用:前端
安裝 single-spa 腳手架工具:npm install create-single-spa@2.0.3 -g
vue
建立微前端容器應用:create-single-spa
java
應用文件夾填寫 containerreact
應用選擇 single-spa root configwebpack
組織名稱填寫 studyweb
組織名稱能夠理解爲團隊名稱,微前端架構容許多團隊共同開發應用,組織名稱能夠標識應用由哪一個團隊開發。vue-router
應用名稱的命名規則爲 @組織名稱/應用名稱
,好比 @study/todos
vue-cli
4. 啓動應用:cd ./singletest && npm start
5. 訪問應用:localhost:9000
src/xx-root-config.js
// 從框架中引入 兩個 方法,下面調用
import { registerApplication, start } from "single-spa";
/* 註冊微前端應用 1. name: 字符串類型, 微前端應用名稱 "@組織名稱/應用名稱" 2. app: 函數類型, 返回 Promise, 經過 systemjs 引用打包好的微前端應用模塊代碼 (umd) 3. activeWhen: 路由匹配時激活應用 */
registerApplication({
name: "@single-spa/welcome",
app: () =>
System.import(
"https://unpkg.com/single-spa-welcome/dist/single-spa-welcome.js"
),
activeWhen: ["/"],
});
複製代碼
// 當前組織的微應用引入示例
// registerApplication({
// name: "@xl/navbar",
// app: () => System.import("@xl/navbar"),
// activeWhen: ["/"]
// });
// start 方法必須在 single spa 的配置文件中調用
// 在調用 start 以前, 應用會被加載, 但不會初始化, 掛載或卸載.
start({
// 是否能夠經過 history.pushState() 和 history.replaceState() 更改觸發 single-spa 路由
// true 不容許 false 容許 (先了解,有印象)
urlRerouteOnly: true,
});
複製代碼
index.ejs
<body>
<main></main>
<!-- 導入微前端容器應用 -->
<script> System.import('@xl/root-config'); </script>
<!-- import-map-overrides 能夠覆蓋導入映射 當前項目中用於配合 single-spa Inspector 調試工具使用. 能夠手動覆蓋項目中的 JavaScript 模塊加載地址, 用於調試. -->
<import-map-overrides-full show-when-local-storage="devtools" dev-libs></import-map-overrides-full>
</body>
複製代碼
<!-- 用於支持 Angular 應用 -->
<!-- <script src="https://cdn.jsdelivr.net/npm/zone.js@0.11.3/dist/zone.min.js"></script> -->
<!-- 用於覆蓋經過 import-map 設置的 JavaScript 模塊下載地址 -->
<script src="https://cdn.jsdelivr.net/npm/import-map-overrides@2.2.0/dist/import-map-overrides.js"></script>
<!-- 判斷是不是本地 -->
<% if (isLocal) { %>
<!-- 模塊加載器 -->
<script src="https://cdn.jsdelivr.net/npm/systemjs@6.8.3/dist/system.js"></script>
<!-- systemjs 用來解析 AMD 模塊的插件 -->
<script src="https://cdn.jsdelivr.net/npm/systemjs@6.8.3/dist/extras/amd.js"></script>
<% } else { %>
<script src="https://cdn.jsdelivr.net/npm/systemjs@6.8.3/dist/system.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/systemjs@6.8.3/dist/extras/amd.min.js"></script>
<% } %>
複製代碼
<script type="systemjs-importmap"> { "imports": { "single-spa": "https://cdn.jsdelivr.net/npm/single-spa@5.9.0/lib/system/single-spa.min.js" } } </script>
<!-- single-spa 預加載 -->
<link rel="preload" href="https://cdn.jsdelivr.net/npm/single-spa@5.9.0/lib/system/single-spa.min.js" as="script">
<!-- Add your organization's prod import map URL to this script's src -->
<!-- <script type="systemjs-importmap" src="/importmap.json"></script> -->
<!-- JavaScript 模塊下載地址 此處可放置微前端項目中的公共模塊 -->
<% if (isLocal) { %>
<script type="systemjs-importmap"> { "imports": { "@xl/root-config": "//localhost:9000/xl-root-config.js" } } </script>
<% } %>
複製代碼
建立應用:create-single-spa
,注意組織及項目名字,後面註冊微應用是會用到
修改應用端口 && 啓動應用
{
"scripts": {
"start": "webpack serve --port 9002",
}
}
複製代碼
啓動應用: npm start
將 React 項目的入口文件註冊到基座應用 (容器應用) 中
\container\src\study-root-config.js :
// React -- todos
registerApplication({
name: "@study/todos",
app: () => System.import("@study/todos"),
activeWhen: ["/todos"]
});
複製代碼
指定微前端應用模塊的引用地址:
(能夠直接訪問對應應用服務器,有提示 URL 加載地址)
<% if (isLocal) { %>
<script type="systemjs-importmap"> { "imports": { "@study/root-config": "//localhost:9000/study-root-config.js", "@study/todos": "//localhost:9002/study-todos.js" } } </script>
<% } %>
複製代碼
指定公共庫的訪問地址,默認狀況下,應用中的 react 和 react-dom 沒有被 webpack 打包, single-spa 認爲它是公共庫,不該該單獨打包。
<script type="systemjs-importmap"> { "imports": { "single-spa": "https://cdn.jsdelivr.net/npm/single-spa@5.9.0/lib/system/single-spa.min.js", "react": "https://cdn.jsdelivr.net/npm/react@17.0.1/umd/react.production.min.js", "react-dom": "https://cdn.jsdelivr.net/npm/react-dom@17.0.1/umd/react-dom.production.min.js" } } </script>
複製代碼
修改默認應用代碼,已獨立頁面展現應用內容
container\src\study-root-config.js
// registerApplication({
// name: "@single-spa/welcome",
// app: () =>
// System.import(
// "https://unpkg.com/single-spa-welcome/dist/single-spa-welcome.js"
// ),
// activeWhen: ["/"],
// });
// 修改默認應用註冊方式,獨立頁面展現應用內容
registerApplication(
"@single-spa/welcome",
() => System.import(
"https://unpkg.com/single-spa-welcome/dist/single-spa-welcome.js"
),
location=>location.pathname === '/'
);
複製代碼
micro\container\src\index.ejs
<body>
<main></main>
<h2>
<!-- 指定應用展現位置 -->
<div id="myreact"></div>
</h2>
<script> System.import('@study/root-config'); </script>
<import-map-overrides-full show-when-local-storage="devtools" dev-libs></import-map-overrides-full>
</body>
複製代碼
micro\todos\src\study-todos.js
const lifecycles = singleSpaReact({
React,
ReactDOM,
// 渲染根組件
rootComponent: Root,
// 錯誤邊界函數
errorBoundary(err, info, props) {
// Customize the root error boundary for your microfrontend here.
return null;
},
// 指定根組件的渲染位置
domElementGetter:()=>document.getElementById('myreact')
});
複製代碼
micro\todos\src\study-todos.js
import React from "react";
import ReactDOM from "react-dom";
// single-spa-react 用於建立使用 React 框架實現的微前端應用
import singleSpaReact from "single-spa-react";
// 用於渲染在頁面中的根組件 就至關於傳統React應用的App.js文件
import Root from "./root.component";
const lifecycles = singleSpaReact({
React,
ReactDOM,
// 渲染根組件
rootComponent: Root,
// 錯誤邊界函數
errorBoundary(err, info, props) {
// Customize the root error boundary for your microfrontend here.
// return null;
return ()=> <div>發生錯誤時此處內容將會被渲染</div>
},
// 指定根組件的渲染位置
domElementGetter:()=>document.getElementById('myreact')
});
// 暴露必要的生命週期函數
export const { bootstrap, mount, unmount } = lifecycles;
複製代碼
準備好兩個路由組件
micro\todos\src\home.js && micro\todos\src\about.js
import React, { Component } from 'react'
export default class home extends Component {
render() {
return (
<div> <h2>什麼是快樂星球</h2> </div>
)
}
}
=========我是兩個組件之間的秀麗華美分割線=============
import React from 'react'
function about() {
return (
<div> <h2>快樂星球就是學習微前端</h2> </div>
)
}
export default about
複製代碼
micro\todos\src\root.component.js
import React from "react";
// 引入路由相關組件
import {BrowserRouter, Switch, Route, Redirect, Link} from "react-router-dom"
// 引入組件
import Home from './home'
import About from './about'
export default function Root(props) {
// return <section>{props.name} is mounted! && 拉勾大前端</section>;
return (
// 使用路由組件,設計基礎路由路徑
<BrowserRouter basename="/todos"> <div>{props.name}</div> {/* 設置點擊連接,跳轉路由 */} <div> <Link to="/home">Home</Link> | <Link to="/about">About</Link> </div> {/* 路由展現 */} <Switch> <Route path="/home"> <Home /> </Route> <Route path="/about"> <About></About> </Route> <Route path="/"> {/* 路由重定向 */} <Redirect to="/home"></Redirect> </Route> </Switch> </BrowserRouter>
)
}
複製代碼
路由文件已公共模塊引入,\micro\container\src\index.ejs
<script type="systemjs-importmap"> { "imports": { "single-spa": "https://cdn.jsdelivr.net/npm/single-spa@5.9.0/lib/system/single-spa.min.js", "react": "https://cdn.jsdelivr.net/npm/react@17.0.1/umd/react.production.min.js", "react-dom": "https://cdn.jsdelivr.net/npm/react-dom@17.0.1/umd/react-dom.production.min.js", "react-router-dom": "https://cdn.jsdelivr.net/npm/react-router-dom@5.2.0/umd/react-router-dom.min.js" } } </script>
複製代碼
修改 webpack 配置文件,排除路由模塊打包,micro\todos\webpack.config.js
return merge(defaultConfig, {
// modify the webpack config however you'd like to by adding to this object
externals: ["react-router-dom"]
});
複製代碼
建立應用:create-single-spa
由於 vue && vue-router 須要經過公共模塊打包,因此,在應用內部須要配置不打包
micro\realworld\vue.config.js
module.exports = {
chainWebpack:config=>{
// 配置不打包 Vue 及 vue-router
config.externals(["vue","vue-router"])
}
}
複製代碼
修改項目啓動命令:micro\realworld\package.json
"scripts": {
"serve": "vue-cli-service serve",
"start": "vue-cli-service serve --port 9003",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"serve:standalone": "vue-cli-service serve --mode standalone"
},
複製代碼
註冊應用:micro\container\src\study-root-config.js
// Vue -- todos
registerApplication({
name: "@study/realworld",
app: () => System.import("@study/realworld"),
activeWhen: ["/realworld"],
});
複製代碼
micro\container\src\index.ejs
加載 vue && vue-router
<script type="systemjs-importmap"> { "imports": { "single-spa": "https://cdn.jsdelivr.net/npm/single-spa@5.9.0/lib/system/single-spa.min.js", "react": "https://cdn.jsdelivr.net/npm/react@17.0.1/umd/react.production.min.js", "react-dom": "https://cdn.jsdelivr.net/npm/react-dom@17.0.1/umd/react-dom.production.min.js", "react-router-dom": "https://cdn.jsdelivr.net/npm/react-router-dom@5.2.0/umd/react-router-dom.min.js", "vue": "https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js", "vue-router": "https://cdn.jsdelivr.net/npm/vue-router@3.0.7/dist/vue-router.min.js" } } </script>
複製代碼
導入應用,應用地址能夠直接訪問應用後,在瀏覽器的提示中獲取;
<% if (isLocal) { %>
<script type="systemjs-importmap"> { "imports": { "@study/root-config": "//localhost:9000/study-root-config.js", "@study/todos": "//localhost:9002/study-todos.js", "@study/realworld": "//localhost:9003/js/app.js" } } </script>
<% } %>
複製代碼
\micro\realworld\src\main.js
import Vue from 'vue';
import singleSpaVue from 'single-spa-vue';
import App from './App.vue';
import VueRouter from 'vue-router'
Vue.use(VueRouter)
// 路由組件
const Foo = { template: "<div>Foooooo</div>" }
const Bar = { template: "<div>Barrrrr</div>" }
// 路由規則
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar },
]
// 路由實例
const router = new VueRouter({ routes, mode: "history", base: "/realworld" })
Vue.config.productionTip = false;
const vueLifecycles = singleSpaVue({
Vue,
appOptions: {
// 註冊路由
router,
render(h) {
return h(App, {
props: {
// 組件傳參
},
});
},
},
});
export const bootstrap = vueLifecycles.bootstrap;
export const mount = vueLifecycles.mount;
export const unmount = vueLifecycles.unmount;
複製代碼
micro\realworld\src\App.vue
<template>
<div id="app">
<div>
<router-link to="/foo">Goto Foo</router-link> |
<router-link to="/bar">Goto Bar</router-link>
</div>
<div>
<router-view></router-view>
</div>
</div>
</template>
複製代碼
用於放置跨應用共享的 JavaScript 邏輯,它也是獨立的應用,須要單獨構建單獨啓動。
建立應用:create-single-spa
in-browser utility module (styleguide, api cache, etc)
修改端口,啓動應用, \micro\tools\package.json
"scripts": {
"start": "webpack serve --port 9005",
}
複製代碼
導出公共方法 : micro\tools\src\study-tools.js
export function happyStar(who){
console.log(`${who} hahahhahahhah`)
return 'happy star 之 快樂的源泉'
}
複製代碼
在模板文件中聲明應用模塊訪問地址 : micro\container\src\index.ejs
<% if (isLocal) { %>
<script type="systemjs-importmap"> { "imports": { "@study/root-config": "//localhost:9000/study-root-config.js", "@study/todos": "//localhost:9002/study-todos.js", "@study/realworld": "//localhost:9003/js/app.js", "@study/tools": "//localhost:9005/study-tools.js" } } </script>
<% } %>
複製代碼
MicroFrontends\micro\todos\src\about.js
import React, { useEffect, useState } from "react";
// 自定義鉤子函數
function useToolsModule() {
const [toolsModule, setToolsModule] = useState();
useEffect(() => {
// 導入,異步promise返回
System.import("@study/tools").then(setToolsModule);
}, []);
return toolsModule;
}
function about() {
var back = "";
// 調用鉤子函數
const toolsModule = useToolsModule();
if (toolsModule) {
// 調用共享邏輯的方法
back = toolsModule.happyStar("React todo");
}
return (
<div> <h2>快樂星球就是學習微前端--{back}</h2> </div>
);
}
export default about;
複製代碼
micro\realworld\src\main.js
// 路由組件
// const Foo = { template: "<div>猜不到吧</div>" };
import Foo from './components/Foo'
const Bar = { template: "<div>仍是快樂星球啊哈哈哈哈</div>" };
複製代碼
micro\realworld\src\components\Foo.vue
<template>
<div>
<h2>什麼是快樂星球 {{ msg }}</h2>
<button @click="getHappy">點我獲取答案</button>
</div>
</template>
<script>
export default {
data() {
return {
msg: "",
};
},
methods: {
async getHappy() {
let toolsModule = await window.System.import("@study/tools");
this.msg = toolsModule.happyStar("Vue");
},
},
};
</script>
<style>
</style>
複製代碼