翻译字符串提取

问题描述 投票:0回答:1

我们已经编写了翻译提取工具,可以提取我们在TypeScript中标记为要翻译的字符串。 JavaScript工具读取我们的Typescript文件,并具有如下正则表达式:

fileContent.match(/this.\translate\((.*?));/);

(简化了可读性,可以正常工作)

翻译方法采用3个参数:1.要翻译的字符串,2.可插值的任何变量,3.描述。后两个是可选的。实现示例:

this.translate('text to translate');
this.translate('long text' + 
               'over multiple lines');
this.translate(`text to translate with backticks for interpolation`);
this.translate(`some test with a ${variable}`, [variable]);
this.translate(`some test with a ${variable}`, [variable], 'Description');

我们需要从JavaScript中的文本中提取这3个参数,并在解析它时遇到问题。我们目前正在使用正则表达式来检查第一个开头字符串字符('或“`”),并尝试匹配结束字符,但这很难做到。

我目前正在尝试使用eval(脚本不是在浏览器中运行,而是在CLI中运行,如下所示:

function getParameters(text, variables, description){ 
    return {text: text, variables: variables, description: description}
}
toEval = string.replace('this.translate', 'getParameters');
eval(toEval);

如果没有变量,哪个效果很好,但是当我们传入变量时抱怨"variables" not defined

有人可以建议一种更好/更好的方式来处理此文本提取吗?

javascript regex string typescript extraction
1个回答
0
投票

代替正则表达式,您可以使用babel或webpack正确解析Javascript(或打字稿)并提取所有信息。

我有一个仅适用于静态字符串的webpack插件,但是应该提供一个很好的起点:https://github.com/grassator/webpack-extract-translation-keys

© www.soinside.com 2019 - 2024. All rights reserved.