Angular 5构建后应用路由时的字体加载异常问题
这个问题的核心和Angular的路由模式、字体资源的引用路径直接相关,我来一步步拆解并给出解决办法:
1. 字体引用路径的相对/绝对问题
首先排查你的字体CSS引用逻辑:如果字体是用相对路径(比如 ./assets/fonts/your-font.ttf)引入的,当你刷新详情页(比如路由是 /ticketBundles/123 这种多层级路径)时,浏览器会把当前URL的层级当成基准路径,去请求 /ticketBundles/assets/fonts/your-font.ttf——但你的字体实际存放在根目录的 assets 下,自然会找不到。
解决方法:
把所有字体引用改成绝对路径,也就是在路径前加上斜杠:
@font-face { font-family: 'YourCustomFont'; src: url('/assets/fonts/your-font.ttf') format('truetype'); /* 其他字体格式(woff/woff2等)同理修改路径 */ }
这样不管当前页面路由是几级,浏览器都会从网站根目录开始定位 assets 下的字体文件,不会出现路径偏移。
2. Angular路由模式的服务器适配问题
Angular默认使用 PathLocationStrategy(无#的干净URL),这种模式下,刷新浏览器时,浏览器会直接向服务器请求当前的路由路径(比如 /ticketBundles/123)。如果你的服务器没有配置「所有路由请求都返回 index.html」,服务器会返回404错误;即使服务器返回了 index.html,页面加载时的相对资源路径也会因为当前URL层级出错,导致字体加载失败。
两种解决方向:
方向一:切换到Hash路由模式
这种模式下URL会带上#(比如 /#/ticketBundles/123),刷新时浏览器不会向服务器请求 /ticketBundles/123,而是直接由Angular接管路由处理,完全避免服务器配置问题。
修改 app.module.ts:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { RouterModule, Routes } from '@angular/router'; // 导入路由策略相关类 import { HashLocationStrategy, LocationStrategy } from '@angular/common'; import { AppComponent } from './app.component'; const routes: Routes = [ // 你的现有路由配置 { path: 'ticketBundles', loadChildren: './ticket-bundles/shared/ticket-bundle.module#TicketBundleModule', data: { roles: ['role.admin', 'role.backoffice'] } }, // 其他路由... ]; @NgModule({ imports: [BrowserModule, RouterModule.forRoot(routes)], declarations: [AppComponent], // 添加Hash路由策略配置 providers: [{ provide: LocationStrategy, useClass: HashLocationStrategy }], bootstrap: [AppComponent] }) export class AppModule { }
方向二:配置服务器支持Path路由模式
如果你想保留干净的URL,需要让服务器把所有路由请求都转发到 index.html。举几个常见服务器的配置例子:
- Nginx:在server块中添加:
location / { try_files $uri $uri/ /index.html; } - Apache:创建
.htaccess文件并添加:RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L] - IIS:配置URL重写规则,将所有非文件/目录的请求重定向到
index.html。
3. 额外检查点
确认 .angular-cli.json(Angular 5的配置文件)里的assets配置正确,确保字体所在的assets/fonts目录被包含在打包资源中:
"assets": [ "assets", "favicon.ico" ]
这样打包时字体文件才会被正确复制到dist目录的对应位置。
内容的提问来源于stack exchange,提问作者Alessandro Celeghin

