Can you “dumb down” ES6 template strings to normal strings?

▼魔方 西西 提交于 2019-11-28 01:52:33

Great question. There are four solutions that come to mind:

1. Brute force

A brute force replacement of backticks with quote marks prior to scanning for translatable strings, as you suggested, is not a horrible idea, as long as you understand the risks. For instance, consider:

"hello, this word is in `backticks`"

Another edge case is

`${`I am nested`}`

This approach will also break multi-line template strings.

2. Fix xgettext

Of course, the "correct" solution is to write a fork of xgettext that deals with template strings. Then you could just write

const something = _(`Look, I am a ${adjective} string`);

Unfortunately, this could be harder that it seems. There is a bunch of hard-wired logic inside xgettext related to strings. If you were to undertake this project, many would thank you.

3. Using a parser

The more robust alternative is to use a JavaScript parser such as Esprima. These parsers expose the ability to pick up tokens (such as template strings). As you can see at http://esprima.org/demo/parse.html, the relevant token type to look for is TemplateLiteral.

4. Unadvisable hacks

Another (bad?) idea is to write template strings as regular strings to start with, then treat them as template strings at run-time. We define a function eval_template:

const template = _("Look, I am a ${adjective} string");
const something = eval_template(template, {adjective});

eval_template converts a string into an evaluated template. Any variable in local scope used in the template string needs to be provided to eval_template as part of the object passed in the second parameter (because functions created using Function are in the global scope and cannot access local variables, so we have to pass them in). It is implemented as follows:

function eval_template_(s, params) {
  var keys = Object.keys(params);
  var vals = keys.map(key => params[key]);

  var f = Function(...keys, "return `" + s + "`");
  return f(...vals);
}

Granted, this is a bit awkward. The only advantage of this approach is that it requires no pre-scan rewriting.

Minor point, but if the original template string is multi-line, you cannot directly rewrite it as a regular string. In that case, you can leave it as a back-ticked template string but escape the $ as \$, and all will be well:

Bottom line: unless you want to rewrite xgettext, use a parser, or engage in other hackery, do the brute force replacement.

Currently, I am working on a localization solution that is based on es6 template literals. You can check out it here - https://c-3po.js.org. This project has extraction functionality (based on the babel plugin). And also you can use it to build localized js. Here is how it looks like:

t`Hello ${name}`
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!