停更已一年多,期间做了很多团队和项目管理的事情。回归初心~
1. 微前端
如何实现多个应用间的资源共享?
方案一: npm包的抽离和引用
缺点
- 开发及效率问题
先发布npm包;更新使用了该npm包的应用;项目构建 - 多团队代码管理问题
不同团队编码风格不同,每引入一个npm包,风格不一致
方案二:微前端
微前端官网:https://micro-frontends.org
定义:
Techniques, strategies and recipes for building a modern web app with multiple teams that can ship features independently.
特点:
- 独立部署
- 增量迁移
- 团队自治
- 松耦合代码
2. single-spa介绍
描述: A javascript router for front-end microservices
官网: https://single-spa.js.org/
3. 安装及项目启动
(1)安装及新建项目并启动
npm i create-single-spa@3.0.2 -g
create-single-spa
完成后执行npm start
,如下图即为成功
(2)错误排查
开始使用create-single-spa@2.0.3完成项目create后,执行npm start
会报以下错误
[webpack-cli] Invalid options object. Dev Server has been initialized using an options object that does not match the API schema.
- options has an unknown property 'firewall'. These properties are valid:
object { allowedHosts?, bonjour?, client?, compress?, devMiddleware?, headers?, historyApiFallback?, host?, hot?, http2?, https?, ipc?, liveReload?, onAfterSetupMiddleware?, onBeforeSetupMiddleware?, onListening?, open?, port?, proxy?, setupExitSignals?, static?, watchFiles?, webSocketServer? }
- options.client has an unknown property 'host'. These properties are valid:
object { logging?, overlay?, progress?, webSocketTransport?, webSocketURL? }
参考https://github.com/single-spa/create-single-spa/issues/309,版本3.0.2则不会出现上述问题。
4. 配置
The single-spa root config consists of the following:
[1] The root HTML file that is shared by all single-spa applications.
[2] The JavaScript that calls singleSpa.registerApplication().
Your root config exists only to start up the single-spa applications.
(1)引入子应用:study-root-config.js
Register Application的属性说明如下:
- name: String, 微前端应用名称“@组织名称/应用名称 ”
- app: Function,return Promise, 通过systemjs引用打包好的微前端应用模块代码
- activeWhen: 路由匹配时激活应用
import {
registerApplication, start } from "single-spa";
registerApplication({
name: "@single-spa/welcome",
app: () =>
System.import(
"https://unpkg.com/single-spa-welcome/dist/single-spa-welcome.js"
),
activeWhen: ["/"],
});
// registerApplication({
// name: "@study/navbar",
// app: () => System.import("@study/navbar"),
// activeWhen: ["/"]
// });
start({
urlRerouteOnly: true,
});
(2)Root HTML file:index.ejs
index.ej中引入基座
5. 新建并引入一个Vue的子应用
(1)创建Vue子应用
create-single-spa
注意type此时需选择single-spa application
项目初始化成功后,修改package.json如下,指定启动9001端口。