【问题标题】:Translation string extraction翻译字符串提取
【发布时间】:2019-12-12 06:13:10
【问题描述】:

我们有一个我们编写的翻译提取工具,它可以提取我们在 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】:

    您可以使用 babel 或 webpack 来正确解析 Javascript(或 typescript)并提取所有信息,而不是正则表达式。

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

    【讨论】:

    • 谢谢,如何使用我提供的示例字符串?
    猜你喜欢
    • 2011-02-26
    • 1970-01-01
    • 2017-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多