You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gulp.watch仅触发一次浏览器刷新,JS新手求助配置问题

Fixing BrowserSync's One-Time Reload Issue in Gulp

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();
    });
}))

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:16:38