官网指南中讲解了如何使用webpack-dev-middleware和express配置自定义服务器,但没有热更新功能。
在官网查找了一下,终于解决了这一问题:
1,必备依赖插件,使用npm/yarn安装即可:(需单独安装webpack-hot-middleware)
"dependencies": {
"clean-webpack-plugin": "^3.0.0",
"express": "^4.17.1",
"html-webpack-plugin": "^4.5.0",
"lodash": "^4.17.20",
"webpack": "^5.10.0",
"webpack-cli": "^4.2.0",
"webpack-dev-middleware": "^4.0.2",
"webpack-hot-middleware": "^2.25.0"
}
2,webpack.config.js配置:(热更新插件内置在webpack中,调用即可)
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const webpack = require('webpack'); module.exports = { mode:'development', entry:[ "./src/index.js","webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=true" ], plugins:[ new CleanWebpackPlugin({cleanStaleWebpackAssets:false}), new HtmlWebpackPlugin({ title:'Development', }), new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin() ], output:{ filename:'[name].bundle.js', path:path.resolve(__dirname,'dist'), publicPath:'/', }, };
3,server.js配置:
const express = require('express'); const webpack = require('webpack'); const webpackDevMiddleware = require('webpack-dev-middleware'); const webpackHotMiddleware = require('webpack-hot-middleware'); const app = express(); const config = require('./webpack.config'); const compiler = webpack(config); app.use( webpackDevMiddleware(compiler, { publicPath:config.output.publicPath, }) ); app.use( webpackHotMiddleware(compiler, { path:'/__webpack_hmr',heartbeat:10 * 1000 }) ) app.get("/",function(req,res){ res.sendFile(__dirname + '/dist/index.html'); }); app.listen(3000, function () { console.log('Example app listening on port 3000! '); });