Created
December 1, 2021 06:22
-
-
Save lichangwei/db333c326d22bfc3ae5b038d3aa11151 to your computer and use it in GitHub Desktop.
extract i18n keys from typescript source code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import ts from 'typescript'; | |
| const filename = ts.findConfigFile(process.cwd(), ts.sys.fileExists, 'tsconfig.json'); | |
| if (!filename) throw Error('tsconfig.json not found'); | |
| const { config } = ts.readConfigFile(filename, ts.sys.readFile); | |
| const { options, fileNames } = ts.parseJsonConfigFileContent(config, ts.sys, process.cwd()); | |
| const program = ts.createProgram({ | |
| options, | |
| rootNames: fileNames, | |
| }); | |
| const typeChecker = program.getTypeChecker(); | |
| const keys = []; | |
| function findI18nCall(node: ts.Node): boolean{ | |
| if (ts.isCallExpression(node)) { | |
| if(['i18n.t', 'i18next.t'].includes(node.expression.getFullText().trim())){ | |
| const firstArgument = node.arguments[0]; | |
| if(ts.isStringLiteral(firstArgument)){ | |
| keys.push(firstArgument.text); | |
| }else if(ts.isTemplateExpression(firstArgument)){ | |
| const spans = firstArgument.templateSpans.map(span => { | |
| const type = typeChecker.getTypeAtLocation(span.literal) as ts.UnionType; | |
| return type.types.map((item)=>(item as ts.LiteralType).value + span.literal.rawText); | |
| }); | |
| spans.unshift([firstArgument.head.rawText]); | |
| keys.push(...join(spans)); | |
| } | |
| return true; | |
| } | |
| } | |
| return false; | |
| } | |
| const transformer = <T extends ts.Node>(context: ts.TransformationContext) => { | |
| return (node: ts.Node) => { | |
| function visit(node: ts.Node){ | |
| const isStop = findI18nCall(node); | |
| if(!isStop){ | |
| return ts.visitEachChild(node, visit, context); | |
| } | |
| } | |
| return ts.visitNode(node, visit); | |
| }; | |
| } | |
| program.getSourceFiles().forEach(sourceFile => { | |
| if(sourceFile.fileName.startsWith('/users/louis/workspace/walle/src/')){ | |
| ts.transform(sourceFile, [transformer]); | |
| } | |
| }); | |
| console.log(Array.from(new Set(keys)).sort()); | |
| function join(array: string[][]) { | |
| return array.reduce((result: string[], array: string[])=>{ | |
| return result.map((s0) => array.map((s1) => `${s0}${s1}`)).flat(); | |
| }, ['']); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment