微前端框架single-spa入门

本文介绍了微前端的两种方案,重点讲解了single-spa的使用,包括安装启动、配置、新建Vue子应用以及容器间的通信。通过实例展示了single-spa的注册、路由配置和Vue应用的集成过程。
摘要由CSDN通过智能技术生成

停更已一年多,期间做了很多团队和项目管理的事情。回归初心~


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端口。

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值