5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

webpack4/html-webpack-pluginでhtmlに変数値を挿入する

Posted at

TL;DR

  • html-webpack-pluginを使ってdistにhtmlファイルを吐かせていた
  • 設定情報はJSONに記述するようにしたのでHTMLの<title>を動的にしてbundleさせたくなった
  • プラグイン公式にexampleがあったのでそのままやって解決

何をしたか

現状

SPAをマウントさせる静的なhtmlをHTTPサーバに置きたかったのでhtml-webpack-pluginをつかって、テンプレートのhtmlファイルを用意して、デプロイディレクトリにhtmlを出力していた。
その他の生成されるCSS/js(SPA)はhtmlにhash付きファイル名でinjectされるようになっている。

pluginの指定

// webpack config抜粋
    new HtmlWebpackPlugin({
      template: './src/index.html',
    }),

src/index.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>ブログタイトル</title>
</head>
<body>
  <div id="main"></div>
</body>
</html>

やりたいこと

SPAで使用する設定値周りをStatic Site generator のそれのようにJSONで持たせることにしたので、htmlの

をJSONファイルを参照して合成するようにしたい

解決策

html-webpack-pluginにexampleがあった
https://github.com/jantimon/html-webpack-plugin/tree/master/examples/template-parameters

  • templateをejsファイルにする
  • templateParametersを指定するとejsと結合してくれる

とのこと

    new HtmlWebpackPlugin({
      template: './src/index.ejs',
      templateParameters: { title: 'ここにjsonをimportしたりして変数を指定できる' },
    }),

src/index.html -> src/index.ejs

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title><%= title %></title>
</head>
<body>
  <div id="main"></div>
</body>
</html>

これでOK。

ちなみに、拡張子が.ejsじゃなくて.htmlでもできんじゃね?って思ってrenameせずにやってみたけど変数挿入リテラルが文字として識別されるだけだった

おまけ

templateParameters の型定義

templateParameters?:
	false
	| ((compilation: compilation.Compilation, assets: TemplateParametersAssets, options: Options) => any)
	| { [key: string]: any };

サンプルには { [key: string]: any } しかないっぽいけど、bundleするときのinput/outputを引数とした関数も指定できるっぽい。

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?