背景
某后台管理项目 乾坤 驱动,由一个主项目通过乾坤的微前端方式引入下属的多个微项目,每个微项目都占据该主项目下的一个二级域名,在本地对某个微项目进行开发时,为了能够模拟多个微项目之间跳转或者模拟微项目子域名的跳转功能,需要用nginx对该子域名进行代理,nginx配置如下:
1 |
|
同时,通过webpackDevServer启动对应子项目的本地服务器,并将webpack和webpack-dev-server所用的PUBLIC_URL设定为nginx代理的二级域名,获得publicUrl的方式如下
1 |
|
但实际使用时,发现当本地页面通过react的跳转等方式进入二级域名的更深层路由后,刷新页面的话,会跳转到对应二级域名的index.html,如:
地址:
如果此时在浏览器中刷新,浏览器地址会变为
为了在本地能够模拟测试和线上环境中的多子项目情况,需要解决该问题
过程
暂时省略,步骤较多
结论
通过排查发现,devServer的配置中,historyApiFallback配置项的值为true,该值在普通Webpack项目中可以正常使用,但在子项目中,会导致路由地址302之后自动跳转到该public_url下的index.html地址,需要将配置改为:
1 | // 子项目public_url,即nginx代理的二级域名 |
修改完成之后,直接刷新页面即可保留在当前页面,但是devServer实际返回给浏览器的是单页应用的index.html,此时单页应用的路由发挥功能,判断路由地址后载入对应页面的js并进行渲染,即可正常使用。