我有一个文件backend-dev.js,这主要是webpack的配置。我使用它从捆绑文件运行我的快速服务器。如果发生任何更改,它都会继续并重新启动服务器。当我更改代码时,是否也可以添加任何配置来自动刷新浏览器?这就是我在backend-dev.js里的东西
const path = require('path');
const webpack = require('webpack');
const spawn = require('child_process').spawn;
const HtmlWebpackPlugin = require('html-webpack-plugin');
const compiler = webpack({
// add your webpack configuration here
entry: './app.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: "bundle.js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['env', 'es2015', 'stage-2']
}
}
}
]
},
/*plugins: [
new HtmlWebpackPlugin({
title: 'Project Demo',
hash: true,
template: './views/index.ejs' // Load a custom template (ejs by default see the FAQ for details)
})
],*/
node: {
__dirname: false
},
target: 'node'
});
const watchConfig = {
// compiler watch configuration
// see https://webpack.js.org/configuration/watch/
aggregateTimeout: 300,
poll: 1000
};
let serverControl;
compiler.watch(watchConfig, (err, stats) => {
if (err) {
console.error(err.stack || err);
if (err.details) {
console.error(err.details);
}
return;
}
const info = stats.toJson();
if (stats.hasErrors()) {
info.errors.forEach(message => console.log(message));
return;
}
if (stats.hasWarnings()) {
info.warnings.forEach(message => console.log(message));
}
if (serverControl) {
serverControl.kill();
}
// change filename to the relative path to the bundle created by webpack, if necessary(choose what to run)
serverControl = spawn('node', [path.resolve(__dirname, 'dist/bundle.js')]);
serverControl.stdout.on('data', data => console.log(data.toString()));
serverControl.stderr.on('data', data => console.error(data.toString()));
});发布于 2022-06-14 02:32:14
优秀的问题:我用以下方式解决了这个问题:
express有两个模块,您可以在不刷新浏览器的情况下安装热刷新,并且它将自动刷新:我留给您我的配置。
npm I肝脏 npm I连接-肝脏
const livereload = require('livereload');
const connectLivereload = require('connect-livereload');
const liveReloadServer = livereload.createServer();
liveReloadServer.watch(path.join(__dirname, '..', 'dist', 'frontend'));
const app = express();
app.use(connectLivereload());

请注意,要监视的文件夹位于dist/前端。更改要监视的文件夹,使其工作:为了监视后端,我使用NODEMON
livereload在后端为浏览器打开一个端口以公开更改:连接是如何发生的?这很容易;使用"connect-livereload“表示并注入一个监视该端口的脚本:如果发生更改,则由express、通知浏览器,浏览器将为您刷新。
我把信息尽可能简单地留给测试,我不建议像这样使用它:要使用它,必须将开发环境和生产环境分开。我把它保持简单,这样容易理解。
在这里,我留下了我发现的最相关的链接:我希望它也会有所帮助。
https://bytearcher.com/articles/refresh-changes-browser-express-livereload-nodemon/
https://stackoverflow.com/questions/43532379
复制相似问题