single-spa Angular微前端路由哈希配置及部署后404故障求助
问题排查与解决方案
一、无法加载子应用脚本的核心原因
你注册子应用的激活规则使用了location.pathname.startsWith("/dashboard")判断,但部署后跳转的URL为https://microfrontend.com/home/#/dashboard/my-dashboard,此时URL的pathname为/home,根本匹配不到/dashboard前缀,因此single-spa判定不需要激活dashboard应用,自然不会发起资源加载请求。
二、针对性修复方案
1. 修正子应用激活规则
根应用root-application.js中修改dashboard和service的激活判断逻辑,适配哈希路由模式:
// dashboard应用激活规则修改为判断hash location => location.hash.startsWith("#/dashboard"), // service应用激活规则同理 location => location.hash.startsWith("#/service"),
2. 修正路由相关配置
- 根应用配置:将
index.html中single-spa-router的base属性改为/home/,适配部署在/home路径的实际场景。 - Navbar跳转逻辑:删除
onNavigation方法中修改window.location.pathname的代码,直接操作hash即可,修改pathname会触发不必要的页面刷新:
onNavigation() { // 删掉window.location.pathname += "/"这行 window.location.hash = "/" + url; }
- Angular子应用路由配置:所有子应用(dashboard、service、navbar)作为single-spa微应用,不能使用
RouterModule.forRoot,要改为RouterModule.forChild,同时关闭子应用自身的哈希路由,由根应用统一管控路由模式:
// dashboard的router.ts修改如下 @NgModule({ // 改为forChild,删除useHash配置 imports: [RouterModule.forChild(routes), { preloadingStrategy: NoPreloading }], exports: [RouterModule], // 不需要配置APP_BASE_HREF,或者配置为'/home/' }) export class AppRoutingModule { }
3. 验证SystemJS导入映射配置
检查根应用index.html中配置的import map,确保子应用的资源路径正确,示例如下:
{ "imports": { "dashboard": "https://microfrontendapp.com/dashboard/main.js", "service": "https://microfrontendapp.com/service/main.js", "navbar": "https://microfrontendapp.com/navbar/main.js" } }
三、刷新404问题的另一种解决方案(History模式)
如果不想使用哈希路由,可以通过配置Apache重写规则解决刷新404问题,不需要改前端路由代码:
- 开启Apache的rewrite模块:执行命令
a2enmod rewrite - 在服务器
/var/www/html目录下新建.htaccess文件,写入以下配置:
<IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /home/index.html [L] </IfModule>
- 重启Apache服务即可,该配置会将所有非静态资源的请求都重定向到根应用的index.html,由single-spa处理路由匹配,刷新页面就不会出现404。
内容的提问来源于stack exchange,提问作者Vyshnavi Muvvala
相关产品推荐
相关产品推荐

