Handlebars.js 预编译

来源:互联网 发布:ubuntu 17.04 163源 编辑:程序博客网 时间:2024/06/06 09:23

转载自 http://keenwon.com/1013.html

通过预编译,可以提前编译你的模板,节省客户端编译的时间,减少需要引入的 Handlebars 库的大小。

开始

第一步,需要安装 nodenpm,在 OSX上:

$ brew install node$ curl https://npmjs.org/install.sh | sh

上一步的前提是你安装了 Homebrew,如果没有的话,先安装:

$ /usr/bin/ruby -e "$(curl -fsSL https://raw.github.com/mxcl/homebrew/go)"

之后,安装 Handlebars npm

$ npm install handlebars -g

使用 -g 标签安装到全局,就可以在任何项目中使用了。

现在就可以使用预编译了

$ handlebars <input> -f <output>

编译器会把模板输入 Handlebars.templates,如果你输入的文件是 person.handlebars,编译器会添加 Handlebars.templates.person,然后可以直接调用:

Handlebars.templates.person(context, options);

如果你使用预编译模板,你只需要引入运行时库

<script src="/libs/handlebars.runtime.js"></script>

仅仅引入运行时库,除了减少下载的大小,另外一点就是,客户端编译常常是性能的瓶颈。

最佳实践

可以使用一些优化设置来预编译模板,首先你可以指定要编译的helpers 列表

handlebars <input> -f <output> -k each -k if -k unless

编译器会最优化的预编 helpers

0 0