Polyfill for javascript template strings

好久不见. 提交于 2021-01-20 04:57:28

问题


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>
`;

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.

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

EDIT: 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.


回答1:


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

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.

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

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.

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.



来源:https://stackoverflow.com/questions/50458898/polyfill-for-javascript-template-strings

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