[html-webpack-plugin] テンプレートif使って出力制御する方法

2 min read
hiroweb developer

背景

webpack の plugin であるhtml-webpack-pluginを使って、html を出力しているが、同テンプレートでも案件によって微妙に出力差が出てきたため、フラグなどで制御したい。

各種モジュールの導入方法などは割愛する。

方法

コード

.env

FLAG=true

(.env 経由じゃなくて、HtmlWebpackPluginに直接渡しても良いが)

webpack.config.js

new HtmlWebpackPlugin({
  filename: "index.html",
  template: "template.html",
  FLAG: process.env.FLAG,
});

template.html

<% if (htmlWebpackPlugin.options.FLG === true){ %>
<div>FLGによって出力したい要素</div>
<% } %>

出力

<div>FLGによって出力したい要素</div>

FLGtrueであれば表示される。

余談

基本的に ejs を同様の記法が書ける模様。

<% var counter = 1; %>
<% while (counter <= 10) { %>
<div>this loop is <%= counter %> time.</p>
<% counter++; %>
<% } %>

<div>this loop is 1 time.</div>
<div>this loop is 2 time.</div>
<div>this loop is 3 time.</div>
<div>this loop is 4 time.</div>
<div>this loop is 5 time.</div>
<div>this loop is 6 time.</div>
<div>this loop is 7 time.</div>
<div>this loop is 8 time.</div>
<div>this loop is 9 time.</div>
<div>this loop is 10 time.</div>

参考: テンプレートエンジン EJS で使える便利な構文まとめ