安裝webpack-dev-server

(webpack版本3.6.0,webpack-dev-server版本2.11.3)注意版本相容問題,不然會有N多錯誤。

 1 npm i [email protected] -D //安裝到本地依賴 

 webpack-dev-server 類似於 node 中的nodemon工具。

在package.json中配置dev --> webpack-dev-server即可使用 npm run dev來執行webpack-dev-server

{
  "name": "webpackStudy",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack-dev-server"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "jquery": "^3.3.1"
  },
  "devDependencies": {
    "webpack": "^3.12.0",
    "webpack-cli": "^3.2.1",
    "webpack-dev-server": "^2.11.3"
  }
}

如圖,成功執行。

然後把index.html中的bundle路徑改為根路徑。/bundle.js

(webpack-dev-server幫我們打包生成的bundle.js檔案並沒有存放到物理磁碟上,只是放在記憶體中,當專案除錯完後手動執行webpack打包一次就可以了)

webpack-dev-server配置命令 

修改配置檔案,使webpack-dev-server執行後自動開啟預設瀏覽器

修改package.json中 ---> "dev": "webpack-dev-server --open --port 3000 --contentBase src --hot"  //open開啟瀏覽器,port設定埠,contentBase設定開啟後的根路徑, hot每次更新程式碼不會重新生成bundle.js而是類似補丁的方式更新修改部分程式碼,並且在瀏覽器可以實現無重新整理過載

配置命令第二種方式:

package.json (使用配置檔案)

{
  "name": "webpackStudy",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev2": "webpack-dev-server --open --port 3000 --contentBase src",
    "dev": "webpack-dev-server"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "jquery": "^3.3.1"
  },
  "devDependencies": {
    "webpack": "^3.12.0",
    "webpack-cli": "^3.2.1",
    "webpack-dev-server": "^2.11.3"
  }
}

webpack.config.js

const path = require('path');
//啟用熱更新的第二步
const webpack = require('webpack');

module.exports = {
    entry: path.join(__dirname, './src/main.js'),
    output: {
        path: path.join(__dirname, './dist'),
        filename: 'bundle.js'
    },
    devServer: { //這是配置webpack-dev-server命令引數的第二種形式
        open: true, //自動開啟瀏覽器
        port: 3000, //設定埠
        contentBase: 'src', //指定託管的根目錄
        hot: true //啟用熱更新的第一步
    },
    plugins: [ //配置外掛的節點
        //啟用熱更新第三步
        new webpack.HotModuleReplacementPlugin() //new一個熱更新的模組物件
    ]
}