Gulp4 watch不监听文件变更问题求助
Let's break down what's going on here and fix your issue. First, I've run into similar headaches with Gulp 4 on Linux systems, so this is likely a combination of Gulp 4's watch behavior and Linux file system quirks—not a bug, just an easy-to-miss gotcha.
First, Rule Out Simple Fixes
Check Gulp Version Consistency: Make sure you're running the local Gulp 4 package, not a global Gulp 3 installation. Run
npx gulp --versionin your project directory—this guarantees you're using the Gulp 4 version you installed locally, not an outdated global copy that might conflict.Fix the Watch Task's Async Handling: In your second Gulp 4 example, you have this:
function watch( done ) { gulp.watch( 'src/style.scss', gulp.series( sass ) ); done(); }Calling
done()tells Gulp thewatchtask is finished, butgulp.watchruns indefinitely to listen for changes. Remove thedone()call here—this keeps the watch task active without signaling premature completion.
The Real Issue: Linux File System Watch Limitations
On CentOS 7, Gulp 4 uses chokidar which relies on inotify by default. The problem? Many editors (like Vim, or Sublime in certain modes) save files by deleting the original file and writing a new one instead of modifying it. This changes the file's inode, and inotify (which monitors inodes) doesn't pick up the change.
The Fix: Enable Polling Mode
To work around this, force gulp.watch to use polling (which checks for file changes at regular intervals, instead of relying on inotify events). Add the usePolling: true option to your watch call:
const gulp = require( 'gulp' ); function sass( done ) { console.log( 'Success!' ); done(); } function watch() { // Enable polling to detect file replacements on Linux gulp.watch( 'src/style.scss', { usePolling: true }, gulp.series( sass ) ); } exports.default = watch; exports.sass = sass;
Test It Out
Run npx gulp (or npx gulp watch if you keep your original export name) and modify src/style.scss with your editor. You should now see the Success! log pop up in your console whenever you save changes.
Why This Worked in Gulp 3
Gulp 3 used a different watch implementation that handled file replacement more gracefully out of the box. Gulp 4 switched to chokidar for better cross-platform support, but this means we have to explicitly enable polling for Linux systems where editors use destructive saves.
内容的提问来源于stack exchange,提问作者A.N.M. Saiful Islam

