LoginSignup
1
2

More than 5 years have passed since last update.

html-webpack-pluginでfront-matterを挿入

Posted at

html-webpack-pluginで生成したhtmlにfront-matterを挿入したい。

以下はhoge/index.htmlpermalink: /hoge/を追加する例。
気が向いたらちゃんとnode moduleにするかもしれない。(汎用的なものがみつからなければ)

var yaml = require('js-yaml');
var filename = 'hoge/index.html'

function InjectPermaLinkPlugin() {
}

InjectPermaLinkPlugin.prototype.apply = function(compiler) {
    compiler.plugin('compilation', function(compilation) {
        compilation.plugin('html-webpack-plugin-after-html-processing', function(htmlPluginData, callback) {
            if (htmlPluginData.outputName == filename) {
                htmlPluginData.html = "---\n" + yaml.dump({permalink: '/hoge/'}) + "---\n" + htmlPluginData.html;
            }
            callback(null, htmlPluginData);
        });
    });
};
var minify = {} // 省略
var config = {
  plugins:[
    new HtmlWebpackPlugin({
      inject: true,
      filename: '2017/index.html',
      template: 'public/2017/index.html',
      minify: minify
    }),
    new InjectPermaLinkPlugin(),
  ]
}

もっとくわしく

いきさつ

GitHub Pages + Jekyllな環境で、hoge.github.io/hoge/みたいなスラッシュで終わるURLにHTMLを表示したい。

/hoge/index.htmlを用意しても表示されなかった。

多分レアケースな状態。

そのためには

---
permalink: "/hoge/"
---

みたいなfront-matterをいれると解決できそうだった。

そこでhtml-webpack-pluginと連携するwebpack pluginを用意した。

調べたこと

minifyする前に挿入してもうまくいかないので、minify後に先頭に挿入する。

ソースコードを確認するとminifyはpostProcessHtmlで処理される。Promiseを返している。
https://github.com/ampedandwired/html-webpack-plugin/blob/v2.24.1/index.js#L274-L296

postProcessHtmlを使っているところを確認。html-webpack-plugin-alter-asset-tagsイベントより後であればminifyされてると考えられる。
https://github.com/ampedandwired/html-webpack-plugin/blob/v2.24.1/index.js#L153

postProcessHtmlより後に発火するイベントを確認する。

  • html-webpack-plugin-after-asset-tags
  • html-webpack-plugin-after-html-processing
  • html-webpack-plugin-after-emit

イベントはhtml-webpack-pluginのREADMEにかいてある。
https://github.com/ampedandwired/html-webpack-plugin#events

html-webpack-plugin-after-html-processingで処理されるのがよさそうな気がする。
https://github.com/ampedandwired/html-webpack-plugin/blob/v2.24.1/index.js#L164

あとはREADMEのevetsの下部にある例を参考にした

1
2
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
1
2