ant design pro 工程切换到非根目录部署 完整实践

要把ant design pro工程发布到非根目录, 例如 /foo这个目录, 期间遇到了不少问题, 记录下面, 避免大家继续趟坑。

作者原创, 如有转载, 请标明出错!

更换配置

  1. 更换发布的路径, 代码里面使用window.baseDir获取当前发布的路径/foo/, 默认的router.config不用添加/foo/, 路由全部在/foo/下面运行
const publicPath = '/foo/';

export default {
...
  manifest: {
    basePath: publicPath,
  },
  base: publicPath, //最终输出路径
  publicPath: publicPath,
...
}
  1. 更换ng的配置, 当然前提是docker编译的时候, 把dist目录拷贝到/usr/share/nginx/html/foo/这个目录
    location /foo/api/ { #如果你的请求全部在/foo下面的话
        proxy_pass https://api-server;
        proxy_set_header Host $proxy_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    location /foo {
        alias /usr/share/nginx/html/foo/;
        try_files $uri /foo/index.html;
    }
  1. 更换dev-server的proxy:
  proxy: {
    [`${publicPath}server/`]: {
      target: 'http://hljwx136.homwee.net/equipmentcenter/',
      changeOrigin: true,
      pathRewrite: { [`^${publicPath}server`]: '' },
    },
  },
  1. 到以上为止, 打包生成的发布文件已经全部ok, 但是开发者模式下yarn start, devServer模式下的umi.js umi.css等文件路径还是不对,需要从根目录切换到/foo
    最后还是读工具的源码, 才发现他使用的webpack的output的publicPath作为umi.js的路径前缀, 又在umi文档找了很久, 无意在英语版本才发现chainWebpack的配置方法
export default {
  chainWebpack: function(config, { webpack }) {
    config.merge({
      output: {
        publicPath: publicPath,
      },
    });
  },
......
  devServer: {
    publicPath: publicPath,
  },
......
}

针对yarn create umi方式创建的工程的更新

2019.8.16
最近发现, 原来拷贝整个pro.antd工程的方式已经不推荐了, 转而使用了yarn create umi的方式来创建一个干净的工程, 然后再根据区块来添加想要的内容模板
针对这个工程, 我发现上面的大部分配置都还是有用的, 需要改变的是chainWebpack的方式, 新的工程已经包含了chainWebpack, 只需要在config/plugin.config.ts里面修改如下:

import { publicPath } from './config';
....
export default (config: any) => {
...
  //change root path
  config.merge({
    output: {
      publicPath: publicPath,
    },
  });
}

2019年8月20日更新

发现src/pages/documents.ejs下面的路径没有更新过来, 做如下修改

    
    

如果帮到了你, 点个

赞!

赠人玫瑰,指尖留香:)

你可能感兴趣的:(ant design pro 工程切换到非根目录部署 完整实践)