# テンプレートのプリコンパイル
Handlebarsプリコンパイラを使用すると、Handlebarsテンプレートを事前にコンパイルして、クライアント側の処理時間を短縮し、Handlebarsライブラリの必要な実行時サイズを削減できます。
# はじめに
まず、Node.jsとnpmが必要です。 https://node.dokyumento.jp/en/download/ (新しいウィンドウで開きます) にアクセスして、お使いのOSでの手順を確認してください。
次に、プリコンパイラを含むHandlebars npmパッケージをインストールします。
npm install -g handlebars
テンプレートを含む`example.handlebars`という名前のファイルを作成します。
プリコンパイラを実行します。
handlebars example.handlebars -f example.precompiled.js
HandlebarsランタイムとプリコンパイルされたJavaScriptを含めます。
<div id="output"></div>
<script src="https://cdn.jsdelivr.net/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()`メソッドに渡す必要があり、結果のオブジェクトは通常どおり使用できます。
# NodeJS内でのテンプレートのプリコンパイル
コマンドラインから「handlebars」を呼び出さずにNodeJS内でテンプレートをプリコンパイルする場合は、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
# 連携
Handlebarsプリコンパイラをビルドシステム(Webpack、Browserifyなど)に統合するために、いくつかのnpmパッケージを使用できます。連携ページをご覧ください。