寫在開始
前面,我們學習了 webpack 的基礎使用,使用命令生成打包后的文件。
但是,每次修改代碼,都要重新運行命令...生成文件...刷新頁面,反復操作。
其實,可以使用 webpack-dev-server 可以很方便的做成服務端,可以完成自動刷新、熱替換等功能。
示例1:命令行
1、安裝
mkdir /你的工作目錄/app-demo
cd /你的工作目錄/app-demo
npm init
npm install webpack webpack-dev-server -g
npm install webpack css-loader style-loader --save-dev
2、創(chuàng)建測試文件
新建 app-demo/entry.js 文件:
require("./styles.css");
document.write('<h2>Hello ,Webpack Dev Server !!!</h2>');
新建 app-demo/styles.css 文件:
body {
background: red;
}
3、運行
webpack-dev-server ./entry --hot --inline --module-bind "css=style\!css"
4、訪問 http://localhost:8080/bundle
此時,我們會看到頁面背景為紅色,可以修改為其他顏色,不用手動刷新可以自動熱更新。
示例2:配置文件
1、安裝
mkdir /你的工作目錄/app-demo-hmr
cd /你的工作目錄/app-demo-hmr
npm init
npm install webpack webpack-dev-server -g
npm install webpack css-loader style-loader --save-dev
2、創(chuàng)建測試文件
新建 app-demo-hmr/src/main.js 入口文件:
require("./styles.css");
document.write('<h2>Hello ,Webpack HMR !!!</h2>');
新建 app-demo-hmr/src/styles.css 文件:
body {
background: red;
}
新建 app-demo-hmr/build/index.html 文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script src="assets/bundle.js"></script>
</body>
</html>
新建配置文件 webpack.config.js
var path = require("path");
var webpack = require("webpack");
module.exports = {
entry: {
app: ["./src/main.js"]
},
output: {
path: path.resolve(__dirname, "build/"),
publicPath: "/assets/",
filename: "bundle.js"
},
module: {
loaders: [{
test: /\.css$/,
loader: 'style!css'
}]
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
devServer: {
contentBase: 'build/',
inline: true,
hot: true
}
};
4、運行命令
webpack-dev-serve

Paste_Image.png
可以看到,項目已啟動,可以正常訪問。并且,在控制臺中啟動了熱替換。
參考
https://segmentfault.com/a/1190000006964335
http://www.tuicool.com/articles/aiEva2Q