Template literals working on other browser except IE

后端 未结 2 426
北恋
北恋 2021-01-16 22:57

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).

相关标签:
2条回答
  • 2021-01-16 23:03

    Template literals are ES6, and IE supports very few ES6 features. It doesn't support template literals.

    For what you're doing, simply do console.log(a) instead:

    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:

    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)

    0 讨论(0)
  • 2021-01-16 23:12

    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.

    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>

    0 讨论(0)
提交回复
热议问题