[webpack] webpack 2 入門: HtmlWebpackPlugin を利用して表示 HTML を自動生成する
bundle された JavaScript を表示するための HTML ファイルを自動生成します。
Installation
開発向けにインストールします。
% yarn add --dev html-webpack-plugin
Configuration
webpack.config.js にプラグインを読み込みます。
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
app: ['./app/index.js', './app/console.js'],
vendors: './app/vendors.js'
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
},
module: {
:
},
plugins: [new HtmlWebpackPlugin()]
};
出力先の調整やテンプレートの利用なども可能です。
Usage
webpack
を実行します。
% $(yarn bin)/webpack
Hash: ef551bd7848118795eac
Version: webpack 2.6.1
Time: 4084ms
Asset Size Chunks Chunk Names
vendors.js 792 kB 0 [emitted] [big] vendors
app.js 5.74 kB 1 [emitted] app
index.html 236 bytes [emitted]
[85] (webpack)/buildin/global.js 509 bytes {0} [built]
[114] ./app/console.js 46 bytes {1} [built]
[115] ./app/index.js 2.36 kB {1} [built]
[116] ./~/babel-polyfill/lib/index.js 833 bytes {0} [built]
[117] ./~/lodash/lodash.js 540 kB {0} [built]
[118] ./app/lib/person.js 356 bytes {1} [built]
[119] ./app/vendors.js 221 bytes {0} [built]
[120] ./~/core-js/fn/regexp/escape.js 107 bytes {0} [built]
[290] ./~/core-js/modules/es7.string.pad-end.js 337 bytes {0} [built]
[291] ./~/core-js/modules/es7.string.pad-start.js 340 bytes {0} [built]
[292] ./~/core-js/modules/es7.string.trim-left.js 215 bytes {0} [built]
[300] ./~/core-js/shim.js 7.38 kB {0} [built]
[301] ./~/regenerator-runtime/runtime.js 24.4 kB {0} [built]
[302] (webpack)/buildin/module.js 517 bytes {0} [built]
[303] multi ./app/index.js ./app/console.js 40 bytes {1} [built]
+ 289 hidden modules
Child html-webpack-plugin for "index.html":
[0] ./~/lodash/lodash.js 540 kB {0} [built]
[1] ./~/html-webpack-plugin/lib/loader.js!./~/html-webpack-plugin/default_index.ejs 538 bytes {0} [built]
[2] (webpack)/buildin/global.js 509 bytes {0} [built]
[3] (webpack)/buildin/module.js 517 bytes {0} [built]
ディフォルトでは output で指定したディレクトリに JavaScript と共に出力されます。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Webpack App</title>
</head>
<body>
<script type="text/javascript" src="vendors.js"></script><script type="text/javascript" src="app.js"></script></body>
</html>