[英]How to auto refresh browser with webpack on change?
我有一個文件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()));
});
很好的問題:我通過以下方式解決了它:
express 有兩個模塊,你可以安裝它來熱刷新而不刷新瀏覽器,它會自動刷新:我把我的配置留給你。
npm 我 livereload
npm 我連接-livereload
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/frontend 中。 更改您要監視的文件夾以使其工作:要監視后端,我正在使用 NODEMON
livereload在后端為瀏覽器打開一個端口以公開更改:連接是如何發生的? 這很容易; express 用“ connect-livereload ”並注入一個監控那個端口的腳本:如果發生變化,express 會通知瀏覽器,瀏覽器會為你刷新。
我留下的信息盡可能簡單以供測試,我不建議這樣使用它:要使用它,您必須將開發和生產環境分開。 我保持簡單,以便於理解。
在這里,我留下了我找到的最相關的鏈接:我希望它也會有所幫助。
https://bytearcher.com/articles/refresh-changes-browser-express-livereload-nodemon/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.