React中如何将.properties翻译文件转换为JSON对象并正常使用
React项目处理.properties格式翻译文件最优方案
你已经在使用i18next处理翻译,完全可以基于现有i18next生态扩展对.properties格式的支持,不需要修改现有开发流程,有两种落地方式可选:
方案1:构建时预转换(推荐,性能最优)
在打包阶段直接把.properties文件转换成i18next原生支持的JSON格式,运行时无额外解析开销,适配你现有的i18next使用习惯。
- 首先安装相关依赖:
properties(解析.properties格式)、lodash(处理key格式与嵌套结构,也可以自己写逻辑替换) - 在打包脚本中加入转换逻辑,示例代码如下:
const fs = require('fs'); const { parse } = require('properties'); const { camelCase, set } = require('lodash'); // 自定义key映射表,可匹配你期望的输出key格式 const customKeyMap = { 'header.shortcuts-screenreader': 'header.screenReaderLabel', 'header.shortcuts-sign-in': 'header.myAccountLabel', 'header.shortcuts-sign-out': 'header.myAccountLogoutLabel', 'header.shortcuts-my-pages': 'header.myAccountPagesLabel', 'header.shortcuts-new-to-the-library': 'header.newToTheLibrary', 'header.shortcuts-join-the-library': 'header.joinTheLibraryLabel' }; // 读取.properties文件 parse(fs.readFileSync('./language.properties', 'utf8'), (err, parsedProps) => { if (err) throw err; const result = {}; Object.entries(parsedProps).forEach(([rawKey, value]) => { // 优先用自定义映射,没有的话自动转驼峰嵌套格式 const finalKey = customKeyMap[rawKey] || rawKey.split('.').map(camelCase).join('.'); set(result, finalKey, value); }); // 输出到i18next加载翻译的目录,直接替换原来的JSON文件即可 fs.writeFileSync('./public/locales/en.json', JSON.stringify(result, null, 2)); });
- 可以把转换命令配置到package.json的
scripts中,在启动开发服务、打包构建或者拉取phrase最新翻译文件时自动执行,全程无需手动介入。
方案2:运行时动态解析(适合小型项目/需要频繁修改.properties文件的场景)
直接给i18next配置自定义解析逻辑,运行时加载.properties文件并自动解析为可用的翻译对象,不需要提前转换。
- 安装依赖:
i18next-http-backend(客户端加载远程翻译文件用)、properties - 修改i18next初始化配置,示例如下:
import i18n from 'i18next'; import { initReactI18next } from 'react-i18next'; import Backend from 'i18next-http-backend'; import { parse } from 'properties'; import { camelCase, set } = require('lodash'); const customKeyMap = { // 同上自定义key映射表 }; i18n .use(Backend) .use(initReactI18next) .init({ // 其他原有i18next配置保持不变,比如lng、fallbackLng等 backend: { // 自定义解析逻辑,加载到.properties文件后自动转换 parse: (fileContent) => { const parsedProps = parse(fileContent); const result = {}; Object.entries(parsedProps).forEach(([rawKey, value]) => { const finalKey = customKeyMap[rawKey] || rawKey.split('.').map(camelCase).join('.'); set(result, finalKey, value); }); return result; } } });
配置完成后直接把.properties文件放到翻译资源目录即可,i18next会自动加载解析。
注意事项
- 如果.properties文件中存在占位符,可以在转换逻辑中统一处理成i18next支持的
{{变量名}}格式,不需要修改原.properties文件 - 两种方案都可以和phrase的导出流程兼容,配置CI/CD后拉取phrase最新翻译资源即可自动完成格式转换,不影响原有国际化工作流
内容的提问来源于stack exchange,提问作者Hani
相关产品推荐
相关产品推荐

