熱更新
- 前言
- 環境
- 目錄
- 未啟動熱更新
-
- 效果
- 代碼
- 啟用熱更新
-
- 效果
- 代碼
前言
webpack
的
webapck-dev-server
包會啟動一個開發伺服器,當修改入口檔案或者入口檔案中引入的其他檔案時,
webpack
會自動編譯入口檔案,然後重新整理整個頁面。然我們僅僅修改了一個檔案就重新整理了整個頁面,這樣的操作太不劃算了,此時可以用到
webpack-dev-server
的熱更新功能。
環境
初始化
安裝必要的包
目錄

未啟動熱更新
效果
當沒有啟用熱更新時效果如下:
可以觀察到,一旦修改了檔案,則浏覽器會自動重新整理頁面。
代碼
public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>webpack4.x</title>
</head>
<body>
</body>
</html>
src/index.js
import str from './source'
console.log(str)
src/source.js
webpack.config.js
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const webpack = require('webpack')
module.exports = {
mode: 'production',
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
devServer: {
port: 9000,
// 自動打開浏覽器
open: true,
// 告訴伺服器從哪裡dist目錄中提供内容
contentBase: './dist'
},
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html'
})
]
}
啟用熱更新
效果
當啟用熱更新時效果如下:
可以觀察到,浏覽器并未重新整理,僅僅更新了修改了的檔案。
代碼
webpack.config.js
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const webpack = require('webpack')
module.exports = {
mode: 'production',
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
devServer: {
// 隻更新修改的部分,而不是重新整理整個頁面
hot: true,
port: 9000,
// 自動打開浏覽器
open: true,
// 告訴伺服器從哪裡dist目錄中提供内容
contentBase: './dist'
},
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html'
}),
// 列印更新的子產品路徑
new webpack.NamedModulesPlugin(),
// 熱更新插件
new webpack.HotModuleReplacementPlugin()
]
}
當啟用熱更新後,需要在
index.js
入口檔案中添加熱更新加載檔案。
src/index.js
import str from './source'
console.log(str)
if (module.hot) {
module.hot.accept('./source', () => {
const str = require('./source').default
console.log(str)
})
}