用于JavaScript模板字符串的Polyfill [英] Polyfill for javascript template strings

查看:49
本文介绍了用于JavaScript模板字符串的Polyfill的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在使用反引号的javascript模板字符串的polyfill?我指的是看起来像这样的代码:

Are there any polyfills for javascript template strings that use a backtick? I'm referring to code that looks like this:

var textTemplate = `
   <h1>My Template String</h1>
   <p>Some more stuf here...</p>
`;

我不希望使用翻译器,例如babel或需要构建步骤的任何其他工具.此外,将模板放在单独的脚本标签内的javascript模板引擎也不适合我.

I do not wish to use a transpiler such as babel or any other tools that require a build step. Additionally, javascript template engines that place the template inside of a separate script tag are not ideal for me either.

我真的很想能够在同一文件中同时使用模板字符串和其他标准ES5代码.这可能吗?

I'd really just like to be able to use template strings alongside otherwise standard ES5 code in the same file. Is this possible?

我特别需要模板字符串才能在IE11中工作.我意识到他们已经在大多数其他浏览器中使用了.我现在也意识到,polyfill不是我想要的正确术语.

I specifically need template strings to work in IE11. I realize they already do in most other browsers. I'm also now aware that polyfill isn't the correct terminology for what I am wanting.

推荐答案

是否存在使用反引号的javascript模板字符串的polyfill?

Are there any polyfills for javascript template strings that use a backtick?

不.您不能为反引号使用新的Javascript语法的polyfill.polyfill不会影响代码的编译或一行代码的执行.它只能影响运行时的函数调用.

No. You can't have a polyfill for new Javascript syntax which the backticks are. A polyfill can't affect the compiling of the code or the execution of a line of code. It can only affect functions calls at run time.

新Javascript语法的解决方案是将新语法转换为ES5兼容代码.

The solution for new Javascript syntax is to transpile from the new syntax to ES5 compatible code.

您甚至无法创建一个执行相同类型的字符串替换的函数(在传递普通的Javascript引号的字符串时),因为该函数实现无法访问反引号模板中通常使用的局部范围变量.

You can't even create a function that would do the same type of string substitution (when passed a normal Javascript quoted string) because the function implementation would not have access to the locally scoped variables that are typically used in backtick templates.

在函数中可以实现其他类型的字符串替换,但是您必须传递要替换的值(例如C中的sprintf,并使用与模板文字不同的语法),而不仅仅是使用变量模板字符串中的名称.

There are other types of string substitution that can be implemented in a function, but you have to pass the values that you want substituted in (like sprintf in C and use a different syntax than the template literals) rather than just use variable names in the template string.

这篇关于用于JavaScript模板字符串的Polyfill的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆