模板引擎
Long long ago, 動態(tài)頁面的兩種渲染方式:
- DOM API操作繁瑣
- innerHTML可讀性和可維護性差
于是出現(xiàn)了模板引擎,例如JavaScript Micro-Templating
實現(xiàn)代碼如下:
// Simple JavaScript Templating`
// John Resig - [https://johnresig.com/](https://johnresig.com/)
(function(){
var cache = {};
this.tmpl = function tmpl(str, data){
// Figure out if we're getting a template, or if we need to
// load the template - and be sure to cache the result.
var fn = !/\W/.test(str) ?
cache[str] = cache[str] || tmpl(document.getElementById(str).innerHTML) :
// Generate a reusable function that will serve as a template
// generator (and which will be cached).
new Function("obj",
"var p=[],print=function(){p.push.apply(p,arguments);};" +
// Introduce the data as local variables using with(){}
"with(obj){p.push('" +
// Convert the template into pure JavaScript
str
.replace(/[\r\t\n]/g, " ")
.split("<%").join("\t")
.replace(/((^|%>)[^\t]*)'/g, "$1\r")
.replace(/\t=(.*?)%>/g, "',$1,'")
.split("\t").join("');")
.split("%>").join("p.push('")
.split("\r").join("\\'")
+ "');}return p.join('');");
// Provide some basic currying to the user
return data ? fn( data ) : fn;
};
})();
使用時輸寫形如下面的代碼:
<script type="text/html" id="item_tmpl">
<div id="<%=id%>" class="<%=(i % 2 == 1 ? " even" : "")%>">
<div class="grid_1 alpha right">
<img class="righted" src="<%=profile_image_url%>"/>
</div>
<div class="grid_6 omega contents">
<p><b><a href="/<%=from_user%>"><%=from_user%></a>:</b> <%=text%></p>
</div>
</div>
</script>
做到了DOM解構(gòu)清晰,所見即所得。
模板引擎性能好需要:
- 體積小
- 支持線下預編譯,成為靜態(tài)JS文件
現(xiàn)在更好的方案
MVVM: DOM Template
React.js: JSX
- all in js(邏輯+內(nèi)容+樣式(可選))
- 利于組件化
Web Components
webpack
Concepts
四個核心概念:
入口(entry)
輸出(output)
loader
插件(plugins)
依賴圖(dependency graph)
按需加載模塊
npm_lifecycle_event
npm 提供一個npm_lifecycle_event變量,返回當前正在運行的腳本名稱,比如dev、build、start等等。所以,可以利用這個變量,在同一個腳本文件里面,為不同的npm scripts命令編寫代碼。
extract-text-webpack-plugin
該插件的三個參數(shù):
use: 指需要什么樣的loader去編譯文件,栗子:原文件是.css,選擇css-loader
fallback: 編譯后用什么loader來提取css文件
publicfile: 用來覆蓋項目路徑,生成該css文件的文件路徑 其實有output就可以了
Reference
handlebars
Differences Between Handlebars.js and Mustache
高性能JavaScript模板引擎原理解析
doT