chinese-code-processor
v1.3.4
Published
[![npm][npm]][npm-url]
Downloads
29
Readme
中文代码提取替换工具
这是一个用与提取和分析替换代码中的中文常量的工具,以方便对现有的代码进行国际化(i18n):
目前支持的语言有:
- ECMAScript
- TypeScript
- HTML(准备支持)
安装
$ npm install -g chinese-code-processor
使用
cn-processor.js <cmd> [args]
Commands:
cn-processor.js extract [pattern] begin extracting
cn-processor.js inject [pattern] begin injecting
Options:
--version Show version number [boolean]
--output, -o [default: "output.json"]
--input, -i [default: "input.json"]
--variable, -v [default: "t"]
--help Show help [boolean]
使用 extract 命令来提取中文,使用 inject 命令来植入 key
示例:
❯ cn-processor extract 'src/**/*.js'
使用 input/output 参数来指定输入输出文件, variable 参数来指定植入的变量名,默认为 t
提取中文
提取数据 examples:
[
...
{
"path": "./tests/ESExtractor/examples/1/input.js",
"location": {
"line": 6,
"column": 15
},
"content": "共享",
"nodeType": "StringLiteral",
"startOffset": 108,
"endOffset": 112,
"isInJSXAttribute": false
},
...
]
则可以把代码中文提取出来,包含了中文应有的信息,透过这些信息,则可以对现有的代码进行替换。 我们只需要在数据中加入一个 "uniqueKey" 字段,则可以透过下述的 inject 方法,把代码重新替换成 t 函数的形式
植入 UniqueKey
把代码中的中文提取出来之后,可以把中文对应的 uniqueKey 填上,然后使用 Injector
可以把代码中相应的中文替换成 t('some_key')
suggestions 数据 examples:
[
...
{
"path": "./tests/ESExtractor/examples/2/input.js",
"location": {
"line": 2,
"column": 15
},
"content": "共享",
"nodeType": "StringLiteral",
"startOffset": 53,
"endOffset": 57,
"isInJSXAttribute": false,
"uniqueKey": "share"
},
...
]
Input:
const VISITOR_PERMISSION_SETTINGS = {
SHAREABLE: '共享',
EDITABLE: '编辑',
COMMENTABLE: '评论',
READABLE: '阅读',
};
Output:
const VISITOR_PERMISSION_SETTINGS = {
SHAREABLE: t('share'),
EDITABLE: t('edit'),
COMMENTABLE: t('comment'),
READABLE: t('read'),
};
编程使用
除了可以透过 cli 使用此工具,还可以通过编程的的方式使用,具体用法可以参考 /tests/
和 /bin/
提取
import { ESExtractor } from 'chinese-code-processor'
import * as fs from 'fs'
const path = "./index.js";
const code = fs.readFileSync(path, "utf8");
const extractor = new ESExtractor("./index.js");
console.log(extractor.analyze(code));
则返回提取的数据格式:
export interface ESInformation {
path: string;
content: string;
startOffset: number;
endOffset: number;
nodeType: string;
location: Location;
isInJSXAttribute: boolean;
}
植入
举起参考 /tests/ESInjector
下面的用法:
const injector = new ESInjector();
const injected = injector.inject(code, suggestions);
其中 suggestions 的格式为:
export interface InjectSuggestion {
content: string;
uniqueKey: string;
startOffset: number;
endOffset: number;
nodeType: string;
isInJSXAttribute: boolean;
}
以完成国际化