简体   繁体   English

在IE以外的其他浏览器上工作的模板文字

[英]Template literals working on other browser except IE

I am working on javascript and using "Template literals", which is working on the Chrome and Firefox, but it is not working on the Internet Explorer(IE). 我正在使用javascript并使用“模板文字”,该模板可在Chrome和Firefox上使用,但不能在Internet Explorer(IE)上使用。

 var a = 10; console.log(`${a}`) 

Template literals are ES6, and IE supports very few ES6 features. 模板文字是ES6,而IE支持的ES6功能很少 It doesn't support template literals. 它不支持模板文字。

For what you're doing, simply do console.log(a) instead: 对于您正在执行的操作,只需执行console.log(a)

 var a = 10; console.log(a) 

But if your real code is more complicated than that, you'll either have to concatenate manually, eg: 但是,如果实际代码比这更复杂,则要么必须手动进行连接,例如:

`foo${somevar}bar${somevar2}baz`

change to 改成

'foo' + somevar + 'bar' + somevar2 + 'baz'

Or, a better option, if you like the syntax of template literals and don't like plain string concatenation, would be to integrate Babel into your build process to transpile ES6+ syntax (including template literals) to ES5 automatically : 或者,一个更好的选择,如果你喜欢的模板文字的语法,不喜欢纯字符串连接,将通天集成到您的构建过程transpile ES6 +语法(包括模板文本) 自动 ES5:

https://babeljs.io/repl/ https://babeljs.io/repl/

(Babel will not only transpile template literals, it'll transpile pretty much all of the newer syntax to ES5, like destructuring, arrow functions, async / await , etc - for larger codebases, it's pretty much essential, allowing the programmers to write in the latest and greatest version of the language while remaining compatible with ancient browsers like IE) (Babel不仅将转换模板文字,还将将几乎所有较新的语法转换为ES5,例如解构,箭头功能, async / await等-对于较大的代码库,这非常重要,允许程序员编写语言的最新和最佳版本,同时仍与IE等旧版浏览器兼容)

Another option is if you already are using lodash to switch to its _.template function which allows a lot more than just templating literal functionality and has wide browser support . 另一个选择是,如果您已经在使用lodash切换到其_.template函数,则该函数不仅可以模板化文字功能,而且还具有wide browser support

 var compiled = _.template('hello ${ user }!'); console.log(compiled({ 'user': 'pebbles' })); // => 'hello pebbles!' 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM