模板引擎
Long long ago, 動(dòng)態(tài)頁(yè)面的兩種渲染方式:
- DOM API操作繁瑣
- innerHTML可讀性和可維護(hù)性差
于是出現(xiàn)了模板引擎,例如JavaScript Micro-Templating
實(shí)現(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;
};
})();
使用時(shí)輸寫形如下面的代碼:
<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)清晰欢顷,所見(jiàn)即所得豪嚎。
模板引擎性能好需要:
- 體積小
- 支持線下預(yù)編譯箫攀,成為靜態(tài)JS文件
現(xiàn)在更好的方案
MVVM: DOM Template
React.js: JSX
- all in js(邏輯+內(nèi)容+樣式(可選))
- 利于組件化
Web Components
webpack
Concepts
四個(gè)核心概念:
入口(entry)
輸出(output)
loader
插件(plugins)
依賴圖(dependency graph)
按需加載模塊
npm_lifecycle_event
npm 提供一個(gè)npm_lifecycle_event變量较屿,返回當(dāng)前正在運(yùn)行的腳本名稱,比如dev涉馁、build汪疮、start等等峭火。所以毁习,可以利用這個(gè)變量,在同一個(gè)腳本文件里面卖丸,為不同的npm scripts命令編寫代碼纺且。
extract-text-webpack-plugin
該插件的三個(gè)參數(shù):
use: 指需要什么樣的loader去編譯文件,栗子:原文件是.css稍浆,選擇css-loader
fallback: 編譯后用什么loader來(lái)提取css文件
publicfile: 用來(lái)覆蓋項(xiàng)目路徑载碌,生成該css文件的文件路徑 其實(shí)有output就可以了
Reference
handlebars
Differences Between Handlebars.js and Mustache
高性能JavaScript模板引擎原理解析
doT