Angular 8生产构建中修改i18n翻译文件请求路径方案
Problem Scenario
I’m deploying my Angular 8 app to http://example.com/my_dir, and added the build argument build --prod --base-href=/my_dir/ which works for most functionality. However, the translation files stored in assets/i18n/ are being requested from the wrong path—they need to be fetched from /my_dir/assets/i18n/ instead of the root. Here’s my current app.module.ts configuration for TranslateModule:
import {TranslateModule, TranslateLoader} from "@ngx-translate/core"; import {TranslateHttpLoader} from "@ngx-translate/http-loader"; // AoT requires an exported function for factories export function HttpLoaderFactory(httpClient: HttpClient) { return new TranslateHttpLoader(httpClient); } imports: [ ..., TranslateModule.forRoot({ loader: { provide: TranslateLoader, useFactory: HttpLoaderFactory, deps: [HttpClient] } }) ]
Solution
This issue happens because TranslateHttpLoader defaults to loading translation files from the root path. When deploying to a subdirectory, you just need to explicitly set the correct base path using the loader’s prefix parameter.
Here’s the updated factory function that fixes the path issue:
// AoT requires an exported function for factories export function HttpLoaderFactory(httpClient: HttpClient) { return new TranslateHttpLoader(httpClient, '/my_dir/assets/i18n/'); }
After making this change, the app will correctly request translation files from /my_dir/assets/i18n/, aligning with your deployment subdirectory structure.
内容的提问来源于stack exchange,提问作者Patryk

