寫(xiě)在開(kāi)始
前面,我們學(xué)習(xí)了 webpack 的基礎(chǔ)使用,使用命令生成打包后的文件。
但是,每次修改代碼,都要重新運(yùn)行命令...生成文件...刷新頁(yè)面,反復(fù)操作。
其實(shí),可以使用 webpack-dev-server 可以很方便的做成服務(wù)端,可以完成自動(dòng)刷新、熱替換等功能。
示例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)建測(cè)試文件
新建 app-demo/entry.js 文件:
require("./styles.css");
document.write('<h2>Hello ,Webpack Dev Server !!!</h2>');
新建 app-demo/styles.css 文件:
body {
background: red;
}
3、運(yùn)行
webpack-dev-server ./entry --hot --inline --module-bind "css=style\!css"
4、訪(fǎng)問(wèn) http://localhost:8080/bundle
此時(shí),我們會(huì)看到頁(yè)面背景為紅色,可以修改為其他顏色,不用手動(dòng)刷新可以自動(dòng)熱更新。
示例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)建測(cè)試文件
新建 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、運(yùn)行命令
webpack-dev-serve
5、訪(fǎng)問(wèn) http://localhost:8080/

Paste_Image.png
可以看到,項(xiàng)目已啟動(dòng),可以正常訪(fǎng)問(wèn)。并且,在控制臺(tái)中啟動(dòng)了熱替換。
參考
https://segmentfault.com/a/1190000006964335
http://www.tuicool.com/articles/aiEva2Q