biu-i18n-cli
v1.0.7
Published
Generate JSON or TypeScript i18n files from Google Sheets and CSV
Readme
biu-i18n-cli
从 Google Sheets 或 CSV 生成 JSON/TypeScript 翻译文件,也可将翻译文件反向转换为 CSV。要求 Node.js 18 或更高版本。
安装
安装为开发依赖后,配置文件可获得完整类型提示:
npm install -D biu-i18n-cli在业务项目的 package.json 中添加:
{
"scripts": {
"i18n": "biu-i18n generate"
}
}配置
在业务项目根目录创建 i18n.config.mjs:
/** @type {import('biu-i18n-cli').I18n.Config} */
const config = {
googleSheetsUrl: 'https://docs.google.com/spreadsheets/d/SHEET_ID',
langConfig: [
{ lang: 'en', file: 'en.json' },
{ lang: 'zh', file: 'zh.json' },
{ lang: 'ph', file: 'ph.ts' },
],
sheets: {
p6: ['P6_WEB', 'P6_RULE'],
},
localesPath: './src/i18n',
localeStructure: (localesPath, _locale, file, site) =>
`${localesPath}/${site}/${file}`,
}
export default configCommonJS 项目使用 i18n.config.cjs,配置内容相同,最后一行改为:
module.exports = config运行:
npm run i18n示例配置将生成:
src/i18n/
└── p6/
├── en.json
├── zh.json
└── ph.ts配置字段
| 字段 | 类型 | 说明 |
| --- | --- | --- |
| googleSheetsUrl | string | Google Sheets 文档地址 |
| langConfig | array | 要生成的语言和对应文件名 |
| langConfig[].lang | string | 工作表中的语言列名 |
| langConfig[].file | string | 输出文件名,仅支持 .json 和 .ts |
| sheets | Record<string, string[]> | 站点名到工作表名称数组的映射 |
| localesPath | string | 翻译文件基础目录 |
| localeStructure | function | 生成每个翻译文件的路径 |
localeStructure 参数依次为:
(localesPath, locale, file, site) => stringlocalesPath:配置中的基础目录。locale:当前语言。file:当前输出文件名。site:sheets中的站点名。
Google Sheet 格式
第一列存放翻译 key,其余列名对应 langConfig[].lang:
| key | zh | en | ph | | --- | --- | --- | --- | | button.save | 保存 | Save | I-save | | dialog.cancel | 取消 | Cancel | Kanselahin |
- 同一站点的多个工作表按照数组顺序合并。
- 后面的工作表出现相同 key 时覆盖前面的值。
- 某个工作表缺少语言列时,仅跳过该工作表的该语言。
- 文件名以
.ts结尾时输出export default { ... } as const。
命令
# 按根目录配置生成
biu-i18n generate
# CSV → JSON
biu-i18n csv-to-json translations.csv locales
# CSV → TypeScript
biu-i18n csv-to-ts translations.csv locales
# JSON → CSV
biu-i18n json-to-csv locales translations.csv
# TypeScript → CSV
biu-i18n ts-to-csv locales translations.csvts-to-csv 支持常规 export default 翻译对象、嵌套对象、注释及单引号/双引号/反引号字符串;嵌套 key 会转换为 messageInfo.RedeemReward 形式,且不会执行源文件代码。
未安装包时也可临时执行,但配置文件不会有类型提示:
npx biu-i18n-cli@latest generate本项目开发
npm install
npm run build
npm test