Can we get away with replacing existing JS templating solutions with ES6 templates?

孤者浪人 提交于 2019-12-05 08:35:41

Template strings in ES6 aren't really related to the various template engines that are implemented in JavaScript.

Most template engines (Underscore, Lodash, Mustache, Handlebars, Jade, etc) all have special syntaxes and special forms. Some might give you the ability to define blocks, use special mark up for various things, or giving you unique tags for logic/looping structures.

ES6 Template Strings give you the full power of JavaScript without asking you to learn a specialized/opinionated template engine.

// underscore
var compiled = _.template("hello: <%= name %>");
compiled({name: 'moe'});
// => "hello: moe"

// ES6 Template String
let name = 'moe';
`hello: ${name}`;
// => "hello: moe"

Notice the ugly <%= %> tags in the underscore template? That's just something underscore invented to solve a "problem"; the "problem" being that before ES6, JavaScript didn't have any sort of string interpolation. People thought it was tedious to write things like

var greeting = "hello";
var name     = "moe";
var emotion  = "depressed";

greeting + ", my name is " + name + ". I feel " + emotion + ".";
// => "hello, my name is moe. I feel depressed."

With ES6, JavaScript gets native string interpolation via ${...}. Pretty much anything can go inside ${} as long as it's valid JavaScript.

let name = "naomik";
let emotion = "happy";
`${greeting || "hi"}, my name is ${name}. I feel ${emotion}.`
// => "hi, my name is naomik. I feel happy."

If you transpile, ES6 get transpiled to native ES5 so it should beat any framework/library performance wise.

ES6

var foo = "foo";
var bar = "bar";
var foobar = `${foo} ${bar}`;

Transpiled

"use strict";

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