首页 > 解决方案 > Angular i18n json 文件中的自动比较检查

问题描述

我在 Angular 应用程序中有 2 个文件en.json和翻译。xx.json常见的想法是在两个文件中为多语言应用程序创建翻译,但有时一些程序员只在其中一个文件中添加翻译,因为他们只用他们的语言测试应用程序。

我正在寻找在两个 JSON 文件中检查相同结构的工具,否则它会引发错误,并且在您为第二语言创建翻译时有助于添加。你知道这方面的任何好的做法、工具或插件吗?我正在使用 WebStorm。

标签: jsonangularinternationalizationwebstormangular-i18n

解决方案


使用一个小的 Node.js 脚本

由于您已经安装了 Angular(这意味着您已经安装了 NPM 和 Node.Js),您可以使用脚本在翻译 JSON 文件中发现不一致的地方。这是它的外观

代码

const fs = require('fs');

// Define your file paths here
const files = ['./english.json', './russian.json']

// Read contents and parse JSON
const filesWithKeys = files.map(f => ({
  name: f,
  content: JSON.parse(fs.readFileSync(f, 'utf8'))
}));

// Gather all the keys used in all files in one array
const allKeys = filesWithKeys.map(f => Object.keys(f.content)).flat();

// Find the missing keys by file
const missingKeysByFile = filesWithKeys.map(f => ({
  name: f.name,
  missingKeys: allKeys.filter(k => !(k in f.content))
})).filter(f => f.missingKeys.length > 0);


// Print the result
missingKeysByFile.forEach(f => {
  console.log(`File "${f.name}" is missing keys [ ${f.missingKeys.join(' ')} ]`);
});

样本输出

File "english.json" is missing keys [ appTitle, contentHeader ]
File "russian.json" is missing keys [ usernameHint ]

推荐阅读