webpack入門_hot-module-replacement

前回はwebpack-devserverで開発ができるようになりました、今回はwebpack-devserverでの開発中にhot-module-replacementでファイルの修正を検出してhot reloadできるようにしたいと思います。

webpack.config.jsには以下の修正を加えます。
- devServerにhot: trueの項目の追加
- pluginsにmnew webpack.HotModuleReplacementPlugin()を追加

webpack.config.jsの全体像は以下のようになります。

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const webpack = require('webpack');


module.exports = {
  entry: {
    app: './src/index.js'
  },
  devtool: 'inline-source-map',
  devServer: {
    contentBase: './dist',
    hot: true
  },
  plugins: [
    new CleanWebpackPlugin(['dist']),
    new HtmlWebpackPlugin({
      title: 'Output Management',
      filename: "index.html",
      template: "./index.html"
    }),
    new webpack.HotModuleReplacementPlugin()
  ],
  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'
        ]
      }
    ]

  }
};

これでwebpack-dev-serverを起動したらファイルの修正を検出してhot reloadされると公式のドキュメントにのっていますが、実際はこの設定がなくてもhot reloadされてるような気もするので詳しくはよくわからないです。

それから、特定のファイルがhot reloadされた時のみ処理を行う場合は、以下のようになります。

if (module.hot) {
  module.hot.accept('./print.js', function() {
    console.log('Accepting the updated printMe module!');
    printMe();
  })
}

cssファイルに対してhot reloadを有効にする場合は、以下のコマンドを実行します。

npm install --save-dev style-loader css-loader