Gulp.watch仅触发一次浏览器刷新,JS新手求助配置问题
Hey there! Let’s get that frustrating one-time reload problem sorted out for you. I remember hitting similar roadblocks when I was starting out with JS build tools, so I totally get how annoying this can be.
The Root of the Problem
When you pass browserSync.reload directly to gulp.watch, it gets executed immediately once, and subsequent file changes don’t trigger it correctly—this is because the function loses the right context or isn’t properly bound for repeated calls.
Solution 1: Wrap Reload in an Anonymous Callback
This is a quick fix that ensures browserSync.reload() gets called fresh every time a file changes:
var gulp = require('gulp'); var browserSync = require('browser-sync'); gulp.task('browserSync', function(){ browserSync.init(null,{ open : false, server : { baseDir : 'site', index : "index.html" } }); console.log("finished browser sync setup"); }); gulp.task('watch', gulp.parallel('browserSync', function() { // Wrap reload in a callback function gulp.watch('site/index.html', function() { browserSync.reload(); }); gulp.watch('site/css/main.css', function() { browserSync.reload(); }); }))
Solution 2: Use BrowserSync’s Built-In Watch (Recommended)
BrowserSync has its own watch method that’s optimized for this exact use case. It handles file monitoring more reliably, and it’s cleaner code:
var gulp = require('gulp'); // Use .create() for the modern, recommended BrowserSync setup var browserSync = require('browser-sync').create(); gulp.task('browserSync', function(){ browserSync.init({ open : false, server : { baseDir : 'site', index : "index.html" } }); console.log("finished browser sync setup"); }); gulp.task('watch', gulp.parallel('browserSync', function() { // Let BrowserSync handle the watching browserSync.watch(['site/index.html', 'site/css/main.css']).on('change', browserSync.reload); }))
Quick Tip for Newbies
Make sure your dependencies are up to date—old versions of Gulp or BrowserSync can cause weird bugs like this. Run this command in your project folder to update them:
npm update gulp browser-sync
Give either of these solutions a try, and your browser should refresh every time you save changes to your HTML or CSS files!
内容的提问来源于stack exchange,提问作者Riley Hemphill

