[英]how to configure webpack HMR with express
package.json腳本:
"scripts": {
"build": "webpack --config config/webpack.prod.config.js",
"dev": "webpack --config config/webpack.dev.config.js && nodemon ./dist/server.js",
"start": "nodemon ./dist/server.js"
}
這是主文件:
服務器.js
import express from "express";
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import config from './config/webpack.dev.config';
const app = express();
const compiler = webpack(config);
app.get("/", (req, res) => {
res.send("Hello");
});
app.use(webpackDevMiddleware(compiler, {
publicPath: config.output.publicPath
}));
app.use(webpackHotMiddleware(compiler));
app.listen(4000, () => console.log("Listening to port 4000"))
我的webpack
配置分為三個文件:
這是 webpack 通用配置:
webpack.common.config.js
module.exports = {
entry: {
server: './server.js'
},
output: {
path: path.join(__dirname, '../dist'),
publicPath: "/",
filename: '[name].js'
},
target: 'node',
externals: [new nodeExternals()],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
},
plugins: [
new CleanWebpackPlugin()
]
}
這是 webpack 開發配置:
webpack.dev.config.js
module.exports = merge(common, {
entry: {
server: ['webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000', './server.js']
},
mode: 'development',
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin()
]
})
這是 webpack 開發配置:
webpack.prod.config.js
module.exports = merge(common, {
mode: 'production'
});
最后這是錯誤:
問題是什么? 如何在 webpack 和 express 中配置熱重載?
將“devServer”屬性添加到您的 webpack:
devServer: {
contentBase: "dist",
hot: true,
stats: { colors: true }
},
然后將其添加到 webpack 的入口點。 在你的項目中它是 server.js
require("webpack-hot-middleware/client?reload=true");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.