前言
前端多项目部署到 Nginx 的同一监听端口下的解决方案,项目由一个主项目和多个子项目组成,主项目和子项目都是单独打包。
主子项目之间是使用的腾讯开源的无界(WebComponent 容器 + iframe 沙箱)前端框架,能够完善的解决适配成本、样式隔离、运行性能、页面白屏、子应用通信、子应用保活、多应用激活、vite 框架支持、应用共享等。
https://wujie-micro.github.io/doc
项目打包设置
在vite.config.js文件中设置 base 路径:
主项目 base 路径设置为默认即可'/':
export default defineConfig(({ command, mode }) => {
  const env = loadEnv(mode, process.cwd());
  return {
    base:'/',
  };
});
子项 base 路径设置为'/sub/':
export default defineConfig(({ command, mode }) => {
  const env = loadEnv(mode, process.cwd());
  return {
    base:'/sub/',
  };
});
Nginx.conf 配置
server {
    listen       80;
    server_name  demo.com;
    # 主项目
    location / {
        root   /usr/web/main/;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
    }
    # 子项目
    location /sub {
        alias /usr/web/sub/;
        try_files $uri $uri/ /sub/index.html last;
        index index.html;
    }
}
注意
1、子项 base 设置的路径和 Nginx.conf 配置的子项目监听路径不一致页面刷新会报如下错:
Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.
2、主项目 location 的是 root,而子项目中的是 alias;
3、子项目 try_files index.html 需要配置前缀路径 /sub。
访问
主项目:http://demo.com
子项目:http://demo.com/sub

