tech.chakapoko.com
Home / Webpack

[Webpack]webpack-dev-serverの使い方

webpack-dev-server を利用すると JavaScript の変更を検知し、ブラウザをリロードせずに変更を反映してくれます。

package.json

{
  "devDependencies": {
    "html-webpack-plugin": "^4.4.1",
    "webpack-cli": "^3.3.12",
    "webpack-dev-server": "^3.11.0"
  }
}

index.html

<html>
  <body>
    <div id="root"></div>
    <script type="text/javascript" src="bundle.js"></script>
  </body>
</html>

index.js

window.onload = function () {
  const message = "Hello";
  document.getElementById("root").textContent = message;
};

webpack.config.js

webpack の設定です。

index.js, index.html は webpack によりビルドされ、成果物は dist/ に出力されます。

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  mode: "development",
  entry: "./index.js",
  devServer: {
    contentBase: "./dist",
  },
  output: {
    filename: "bundle.js",
    path: path.resolve(__dirname, "dist"),
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "./index.html",
    }),
  ],
};

実行

$ yarn install
$ yarn webpack --watch &
$ yarn webpack-dev-server --open

index.js を変更するとブラウザのリロードなしで変更が反映されることを確認できます。