问题
One very attractive feature of ES6 is its built in template strings. At this point in time, since transpiling to ES5 is a must for cross browser compatibility, I am curious what the performance differences are between transpiled ES6 templates and existing solutions such as Mustache, Handlebars, Jade etc. Obviously if you need advanced features from a templating language, ES6 templates may not fulfill all of your needs, but if you are performing basic templating, is it fair to say that ES6 template strings could replace your current templating engine?
回答1:
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."
回答2:
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;
来源:https://stackoverflow.com/questions/34058667/can-we-get-away-with-replacing-existing-js-templating-solutions-with-es6-templat