You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中如何将多语言XLIFF文件转为JSON并实现单构建多语言运行加载

实现单次XLIFF构建生成多语言JSON并支持Angular运行时切换

一、XLIFF批量转多语言JSON的构建脚本

用Node.js编写脚本,一次性解析所有目标语言的XLIFF文件,输出对应语言的JSON:

  1. 安装依赖:
npm install xml2js --save-dev
  1. 编写构建脚本(scripts/xliff-to-json.js):
const fs = require('fs');
const path = require('path');
const xml2js = require('xml2js');

// 配置:XLIFF文件目录和输出JSON目录
const xliffDir = path.resolve(__dirname, '../src/locales');
const outputDir = path.resolve(__dirname, '../assets/i18n');

// 确保输出目录存在
if (!fs.existsSync(outputDir)) {
  fs.mkdirSync(outputDir, { recursive: true });
}

// 遍历XLIFF文件
fs.readdirSync(xliffDir).forEach(file => {
  if (file.endsWith('.xlf')) {
    // 提取语言代码(比如messages.fr.xlf → fr)
    const lang = file.split('.')[1];
    const filePath = path.join(xliffDir, file);
    const xmlContent = fs.readFileSync(filePath, 'utf8');

    // 解析XLIFF
    xml2js.parseString(xmlContent, (err, result) => {
      if (err) throw err;
      const translations = {};
      
      // 遍历所有翻译单元
      result.xliff.file[0].body[0]['trans-unit'].forEach(unit => {
        const id = unit.$.id;
        // 取目标语言文本,没有则用源文本
        const text = unit.target?.[0]?._ || unit.source[0]._;
        translations[id] = text;
      });

      // 写入JSON文件
      fs.writeFileSync(
        path.join(outputDir, `${lang}.json`),
        JSON.stringify(translations, null, 2),
        'utf8'
      );
      console.log(`Generated ${lang}.json successfully`);
    });
  }
});
  1. 在package.json中添加构建命令:
{
  "scripts": {
    "i18n:build": "node scripts/xliff-to-json.js"
  }
}

执行npm run i18n:build就能一次性生成所有语言的JSON文件。

二、Angular运行时多语言切换实现

1. 创建翻译服务(src/app/services/translation.service.ts)

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class TranslationService {
  private currentLang = new BehaviorSubject<string>('en');
  private translations = new BehaviorSubject<{ [key: string]: string }>({});

  currentLang$: Observable<string> = this.currentLang.asObservable();
  translations$: Observable<{ [key: string]: string }> = this.translations.asObservable();

  constructor(private http: HttpClient) {
    // 初始化加载默认语言
    this.loadTranslations(this.currentLang.value);
  }

  loadTranslations(lang: string): void {
    this.http.get<{ [key: string]: string }>(`/assets/i18n/${lang}.json`).subscribe(trans => {
      this.translations.next(trans);
      this.currentLang.next(lang);
      // 更新HTML lang属性
      document.documentElement.lang = lang;
    });
  }

  translate(key: string): string {
    return this.translations.value[key] || key;
  }
}

2. 创建翻译管道(src/app/pipes/translate.pipe.ts)

import { Pipe, PipeTransform } from '@angular/core';
import { TranslationService } from '../services/translation.service';

@Pipe({ name: 'translate', pure: false })
export class TranslatePipe implements PipeTransform {
  constructor(private translationService: TranslationService) {}

  transform(key: string): string {
    return this.translationService.translate(key);
  }
}

3. 在组件中使用切换功能

比如在头部组件添加语言切换按钮:

<!-- src/app/components/header/header.component.html -->
<button (click)="switchLang('en')">English</button>
<button (click)="switchLang('fr')">Français</button>
<button (click)="switchLang('es')">Español</button>

<!-- 使用翻译管道 -->
<h1>{{ 'welcome.title' | translate }}</h1>
// src/app/components/header/header.component.ts
import { Component } from '@angular/core';
import { TranslationService } from '../../services/translation.service';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html'
})
export class HeaderComponent {
  constructor(private translationService: TranslationService) {}

  switchLang(lang: string): void {
    this.translationService.loadTranslations(lang);
  }
}

4. 配置模块

确保在AppModule中导入HttpClientModule和声明管道:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { TranslatePipe } from './pipes/translate.pipe';
import { AppComponent } from './app.component';
import { HeaderComponent } from './components/header/header.component';

@NgModule({
  declarations: [AppComponent, HeaderComponent, TranslatePipe],
  imports: [BrowserModule, HttpClientModule],
  bootstrap: [AppComponent]
})
export class AppModule {}

三、注意事项

  • 确保XLIFF文件命名规范,比如messages.en.xlf、messages.fr.xlf,方便脚本提取语言代码
  • 翻译服务中可添加错误处理,比如JSON加载失败时回退到默认语言
  • 可以结合localStorage保存用户上次选择的语言,下次打开自动加载

内容的提问来源于stack exchange,提问作者jrnjy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 06:23:24