Defining Configuration for HMR

HMR 的相關設定可以從 webpack.config.js 抽離出來變成一個 patial 的概念,這樣可以重複使用,或甚至可以用在其他專案上,保持 webpack.config.js 結構簡潔。

所以建立一個 libs/parts.js,把 HMR 相關設定放在裡面。

libs/parts.js

const webpack = require('webpack');

exports.devServer = function(options) {
  return {
    devServer: {
      // Enable history API fallback so HTML5 History API based
      // routing works. This is a good default that will come
      // in handy in more complicated setups.
      historyApiFallback: true,

      // Unlike the cli flag, this doesn't set
      // HotModuleReplacementPlugin!
      hot: true,
      inline: true,

      // Display only errors to reduce the amount of output.
      stats: 'errors-only',

      // Parse host and port from env to allow customization.
      //
      // If you use Vagrant or Cloud9, set
      // host: options.host || '0.0.0.0';
      //
      // 0.0.0.0 is available to all network devices
      // unlike default `localhost`.
      host: options.host, // Defaults to `localhost`
      port: options.port // Defaults to 8080
    },
    plugins: [
      // Enable multi-pass compilation for enhanced performance
      // in larger projects. Good default.
      new webpack.HotModuleReplacementPlugin({
        multiStep: true
      })
    ]
  };
}

然後再到 webpack.config.js 引入 parts.js:

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const merge = require('webpack-merge');
const validate = require('webpack-validator');


const parts = require('./libs/parts');


...

// Detect how npm is run and branch based on that
switch(process.env.npm_lifecycle_event) {
  case 'build':
    config = merge(common, {});
    break;
  default:

    //config = merge(common, {}); // 移除這行


    config = merge(
      common,
      parts.devServer({
        // Customize host/port here if needed
        host: process.env.HOST,
        port: process.env.PORT
      })
    );

}

module.exports = validate(config);

然後執行 npm start,瀏覽 localhost:8080,試著修改 app/component.js 裡面的內容,現在只要你改了,瀏覽器就會馬上同步更新了。

results matching ""

    No results matching ""