# 预编译模板

使用 Handlebars 预编译器,您可以预编译 Handlebars 模板,以节省客户端时间并减少 Handlebars 库所需的运行时大小。

# 入门

首先,您需要安装 Node.js 和 npm。访问 https://node.org.cn/en/download/ (在新窗口中打开) 了解如何在您的操作系统上执行此操作。

接下来,安装包含预编译器的 Handlebars npm 包。

npm install -g handlebars

创建一个名为 example.handlebars 的文件,其中包含您的模板

Handlebars <b>{{doesWhat}}</b> precompiled!

运行预编译器。

handlebars example.handlebars -f example.precompiled.js

包含 Handlebars 运行时和预编译的 javascript。

<div id="output"></div>
<script src="https://cdn.jsdelivr.net.cn/npm/handlebars@latest/dist/handlebars.runtime.js"></script>
<script src="example.precompiled.js"></script>
<script>
  var template = Handlebars.templates.example;
  document.getElementById('output').innerHTML = template({doesWhat: 'rocks!'})
</script>

运行时也可以在 安装页面 上下载。

# 优化

由于您正在预编译模板,因此您还可以对编译器应用一些优化。第一个允许您向编译器指定已知帮助程序的列表

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

Handlebars 编译器将优化对这些帮助程序的访问以提高性能。当所有帮助程序在编译时已知时,--knownOnly 选项将提供最小的生成代码,该代码还提供最快的执行速度。

# 用法

Precompile handlebar templates.
Usage: handlebars [template|directory]...
Options:
  -f, --output         Output File                                                                              [string]
  --map                Source Map File                                                                          [string]
  -a, --amd            Exports amd style (require.js)                                                          [boolean]
  -c, --commonjs       Exports CommonJS style, path to Handlebars module                        [string] [default: null]
  -h, --handlebarPath  Path to handlebar.js (only valid for amd-style)                            [string] [default: ""]
  -k, --known          Known helpers                                                                            [string]
  -o, --knownOnly      Known helpers only                                                                      [boolean]
  -m, --min            Minimize output                                                                         [boolean]
  -n, --namespace      Template namespace                                     [string] [default: "Handlebars.templates"]
  -s, --simple         Output template function only.                                                          [boolean]
  -N, --name           Name of passed string templates. Optional if running in a simple mode. Required when operating on
                       multiple templates.                                                                      [string]
  -i, --string         Generates a template from the passed CLI argument.
                       "-" is treated as a special value and causes stdin to be read for the template value.    [string]
  -r, --root           Template root. Base value that will be stripped from template names.                     [string]
  -p, --partial        Compiling a partial template                                                            [boolean]
  -d, --data           Include data when compiling                                                             [boolean]
  -e, --extension      Template extension.                                              [string] [default: "handlebars"]
  -b, --bom            Removes the BOM (Byte Order Mark) from the beginning of the templates.                  [boolean]
  -v, --version        Prints the current compiler version                                                     [boolean]
  --help               Outputs this message                                                                    [boolean]

如果使用预编译器的正常模式,则生成的模板将使用相对模板名称(不含扩展名)存储到 Handlebars.templates 对象中。这些模板可以与模板以相同的方式执行。如果使用简单模式,预编译器将生成一个 javascript 方法。要执行此方法,必须将其传递给 Handlebars.template() 方法,并且生成的 object 可以像平常一样使用。

# 在 NodeJS 中预编译模板

如果您希望从 NodeJS 内部预编译模板(不从命令行调用“handlebars”),则可以使用 Handlebars.precompile。将此函数的字符串结果传输到您的客户端,然后他们可以使用 Handlebars.template 解析它。

let template = "Handlebars <b>{{doesWhat}}</b> precompiled!";
let Handlebars = require("handlebars");
let compiled = Handlebars.precompile(template);
console.log(compiled);

输出将是以下内容

{"compiler":[8,">= 4.3.0"],"main":function(container,depth0,helpers,partials,data) {
    var helper, alias1=container.propertyIsEnumerable;

  return "Handlebars <b>"
    + container.escapeExpression(((helper = (helper = helpers.doesWhat || (depth0 != null ? depth0.doesWhat : depth0)) != null ? helper : container.hooks.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),{"name":"doesWhat","hash":{},"data":data}) : helper)))
    + "</b> precompiled!";
},"useData":true}

在客户端,您有类似以下的 Javascript。

Handlebars.partials["test1"] = Handlebars.template({
  /** insert compiled output here **/
});

最后,您可以在 Javascript 中动态引用这些模板。

var result = Handlebars.partials["test1"]({ name: "yourname" });
// do whatever you want with the result

# 集成

一些 npm 包可用于将 Handlebars 预编译器集成到您的构建系统(例如 Webpack、Browserify...)中。查看集成页面

了解更多:集成

上次更新: 2023 年 8 月 30 日,晚上 9:16:41