如何让ngx-translate翻译文件置于Electron编译后的可执行文件旁
解决Angular-Electron中ngx-translate翻译文件外置及动态路径配置问题
一、配置electron-builder将翻译文件复制到可执行文件旁的language目录
直接在files字段添加路径会把文件打包进app.asar,无法外部修改。需要用extraResources字段指定外置复制规则:
修改electron-builder.json(或package.json里的build字段):
{ "build": { "extraResources": [ { "from": "src/assets/i18n", "to": "language" } ], // 其他已有配置... } }
这样编译后,src/assets/i18n下的所有文件会被复制到可执行文件所在目录的language文件夹中,且不会被打包进asar,支持外部修改。
二、动态配置ngx-translate的翻译文件路径
需要区分开发模式和Electron生产打包模式,分别加载对应路径的翻译文件:
1. 环境标识辅助判断(可选)
修改src/environments/environment.ts(开发环境):
export const environment = { production: false, isElectron: false };
修改src/environments/environment.prod.ts(生产环境):
export const environment = { production: true, isElectron: true };
2. 自定义TranslateLoader动态切换路径
创建src/app/custom-translate-loader.ts:
import { TranslateLoader } from '@ngx-translate/core'; import { HttpClient } from '@angular/common/http'; import { environment } from '../environments/environment'; import { Observable } from 'rxjs'; export class CustomTranslateLoader implements TranslateLoader { constructor(private http: HttpClient) {} getTranslation(lang: string): Observable<any> { let path = ''; if (!environment.production) { // 开发模式:使用assets下的默认路径 path = `assets/i18n/${lang}.json`; } else { // Electron生产模式:获取可执行文件所在目录,拼接language路径 const electron = window.require('electron'); const exePath = electron.app.getPath('exe'); const pathModule = window.require('path'); const appDir = pathModule.dirname(exePath); path = `${appDir}/language/${lang}.json`; } return this.http.get(path); } }
3. 在AppModule中注册自定义Loader
修改src/app/app.module.ts:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HttpClientModule, HttpClient } from '@angular/common/http'; import { TranslateModule, TranslateLoader } from '@ngx-translate/core'; import { CustomTranslateLoader } from './custom-translate-loader'; export function createTranslateLoader(http: HttpClient) { return new CustomTranslateLoader(http); } @NgModule({ declarations: [/* 你的组件声明 */], imports: [ BrowserModule, HttpClientModule, TranslateModule.forRoot({ loader: { provide: TranslateLoader, useFactory: createTranslateLoader, deps: [HttpClient] } }) ], providers: [], bootstrap: [/* 你的根组件 */] }) export class AppModule { }
注意事项
- Electron中使用
window.require需要在main进程的BrowserWindow配置里开启Node.js集成:webPreferences: { nodeIntegration: true, contextIsolation: false }(生产环境若需更高安全性,可改用preload脚本传递路径)。 - 测试生产模式时,需先执行
ng build --prod再打包Electron,确保翻译文件被正确复制。
内容的提问来源于stack exchange,提问作者Nils
相关产品推荐
相关产品推荐

