webpack入門_html-webpack-plugin
前回に引き続き、今回はbuildでhtmlを出力できるようにしたいと思います。使用するライブラリはhtml-webpack-pluginでbuildの時に必要になるものなので以下のコマンドを実行します。
npm install --save-dev html-webpack-plugin
それからwebpack.config.jsにhtml-webpack-plugin関連の内容を追加します。
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: { app: './src/index.js' }, plugins: [ new HtmlWebpackPlugin({ title: 'Output Management', filename: "index.html", template: "./index.html" }) ], output: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist') }, module: { rules: [ { test: /\.css$/, use: [ 'style-loader', 'css-loader' ] }, { test: /\.(png|svg|jpg|gif)$/, use: [ 'file-loader' ] }, { test: /\.(csv|tsv)$/, use: [ 'csv-loader' ] }, { test: /\.xml$/, use: [ 'xml-loader' ] } ] } };
今回はエントリーポイントが複数になってもHtmlWebpackPluginにより自動でhtml側にscripttタグを追加して読み込ませるようにします。また、テンプレートのhtmlと出力するファイル名を指定しています。
テンプレートのhtmlファイルは以下のように定義します。
<!doctype html> <html> <head> <title>Output Management</title> </head> <body> </body> </html>
それからエントリーポイントとなるsrc/index.jsとsrc/print.jsを以下のように作成します。
src/index.js
import _ from 'lodash'; import printMe from './print.js'; function component() { var element = document.createElement('div'); var btn = document.createElement('button'); element.innerHTML = _.join(['Hello', 'webpack'], ' '); btn.innerHTML = 'Click me and check the console!'; btn.onclick = printMe; element.appendChild(btn); return element; } document.body.appendChild(component());
src/print.js
export default function printMe() { console.log('I get called from print.js!'); }
それからbuildすると作成したdist/index.html内に自動でscriptタグが追加されていることが確認できます。
npm run build
現在のdistディレクトリはbuild時に以前のファイルが残っていて煩雑になっているので、clean-webpack-pluginを入れてビルド時にdistディレクトリをcleanするようにします。
npm install clean-webpack-plugin --save-dev
webpack.config.jsを以下のように修正します。
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const CleanWebpackPlugin = require('clean-webpack-plugin'); module.exports = { entry: { app: './src/index.js' }, plugins: [ new CleanWebpackPlugin(['dist']), new HtmlWebpackPlugin({ title: 'Output Management', filename: "index.html", template: "./index.html" }) ], output: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist') }, module: { rules: [ { test: /\.css$/, use: [ 'style-loader', 'css-loader' ] }, { test: /\.(png|svg|jpg|gif)$/, use: [ 'file-loader' ] }, { test: /\.(csv|tsv)$/, use: [ 'csv-loader' ] }, { test: /\.xml$/, use: [ 'xml-loader' ] } ] } };
これによりbuild実行時にdistディレクトリが毎回cleanされるようになります。