微应用部署说明文档

该文档仅限于基座应用以及微应用的路由都使用 hash 模式的微应用部署

该文档仅限于微应用部署到同一个服务器(同一个 IP 和端口)

一、打包

通常的做法是主应用部署在一级目录,微应用部署在二/三级目录。

微应用想部署在非根目录,在微应用打包之前必须配置 webpack 构建时的 publicPath目录名称

部署之后注意三点:

  1. activeRule 不能和微应用的真实访问路径一样,否则在主应用页面刷新会直接变成微应用页面。
  2. 微应用的真实访问路径就是微应用的 entryentry 可以为相对路径。
  3. 微应用的 entry 路径最后面的 / 不可省略,否则 publicPath 会设置错误,例如子项的访问路径是 http://localhost:8080/app1,那么 entry 就是 http://localhost:8080/app1/

二、部署

1.微应用都放在在一个特殊名称(不会和微应用重名)的文件夹下

假设我们有一个主应用和 2 个微应用(分别为 heaven-sub-app1heaven-sub-app1 ),打包后如下放置:

  1. └── html/ # 根文件夹
  2. |
  3. ├── child/ # 存放所有微应用的文件夹
  4. | ├── heaven-sub-app1/ # 存放微应用 heaven-sub-app1 的文件夹
  5. | ├── heaven-sub-app2/ # 存放微应用 heaven-sub-app2 的文件夹
  6. ├── index.html # 主应用的index.html
  7. ├── css/ # 主应用的css文件夹
  8. ├── js/ # 主应用的js文件夹

此时需要设置微应用构建时的 publicPath,然后才能打包放到对应的目录里。

项目 publicPath 真实访问路径
heaven-sub-app1 /child/heaven-sub-app1/ http://localhost:8080/child/heaven-sub-app1/
heaven-sub-app2 /child/heaven-sub-app2/ http://localhost:8080/child/heaven-sub-app2/

此时 heaven-sub-app1 vue.config.js 代码是这样的。注:${name} 为当前项目名称。

  1. const { defineConfig } = require('@vue/cli-service');
  2. const path = require('path');
  3. const { name } = require('./package.json');
  4. const resolve = (dir) => path.join(__dirname, dir);
  5. module.exports = defineConfig({
  6. publicPath: `/child/${name}`,
  7. devServer: {
  8. port: 9081,
  9. // 允许跨域让基座加载子应用
  10. headers: {
  11. 'Access-Control-Allow-Origin': '*'
  12. }
  13. },
  14. transpileDependencies: true,
  15. chainWebpack: (config) => {
  16. // 配置别名
  17. config.resolve.alias.set('@', resolve('src'));
  18. },
  19. configureWebpack: {
  20. // 配置打包格式
  21. output: {
  22. library: `${name}-[name]`,
  23. libraryTarget: 'umd',
  24. // 后续 libraryTarget 可能会废弃
  25. // library: {
  26. // name: `${name}-[name]`,
  27. // type: 'umd'
  28. // },
  29. // webpack5 jsonpFunction 已废弃
  30. // jsonpFunction: `webpackJsonp_${name}`
  31. chunkLoadingGlobal: `webpackJsonp_${name}`
  32. }
  33. }
  34. });

2.此时nginx配置是这样的。

  1. server {
  2. listen 80;
  3. server_name localhost;
  4. location / {
  5. root /home/html/heaven-main-app;
  6. index index.html index.htm;
  7. }
  8. ......
  9. }

至此主应用已经和微应用都能跑起来了。