【发布时间】:2020-06-07 19:08:52
【问题描述】:
我有一个 React + Webpack + Express 设置。 React 文件由 Webpack 打包并存储在 /dist 目录中。在开发模式下,Webpack 在后台以监视模式运行。新的更改在 dist 目录中更新。 Express 服务器与 Webpack 进程分开运行。根据请求localhost:3000/,Express 服务器向客户端发送dist/index.html 文件。
我想在 Webpack watcher 每次编译完 React 文件(前端)时启用页面重新加载。到目前为止,我所看到的是人们通过 webpack 热重新加载 express 服务器,当发生一些变化时,但这并没有更新客户端。
当 Webpack 重新捆绑前端代码时,有没有办法热重载客户端(通过 Express?)?
webpack.config.js
const path = require('path');
const Dotenv = require('dotenv-webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
mode: 'development',
devtool: 'source-map',
entry: {
main: './src/index.js',
vendor: ['semantic-ui-react'],
},
output:{
path: path.join(__dirname, '/dist'),
filename: '[name].js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.scss$/i,
use: [{
loader: "style-loader"
}, {
loader: "css-loader", options: {
sourceMap: true
}
}, {
loader: "sass-loader", options: {
sourceMap: true
}
}]
},
{
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
use: {
loader: 'url-loader',
options: {
limit: 100000,
},
},
},
{
test: /\.css$/,
include: /node_modules/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
// you can specify a publicPath here
// by default it uses publicPath in webpackOptions.output
publicPath: '../',
hmr: process.env.NODE_ENV === 'development',
},
},
'css-loader',
]
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
}),
new Dotenv(),
new MiniCssExtractPlugin('styles.css')
]
};
server.js
const express = require('express');
const axios = require('axios');
const app = express();
const port = 3000;
app.set('view engine', 'ejs');
app.use(express.static('dist'));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/dist/index.html');
});
app.listen(port, () => console.log('App listening on port 3000!'));
【问题讨论】:
标签: javascript reactjs express webpack