这些包分为两类核心工具:模块打包器(Bundler)和文件监听器(Watcher)。webpack、rollup、parcel 和 browserify 负责将多个模块合并为浏览器可执行的代码,处理依赖解析和代码转换;chokidar、watchify、grunt-contrib-watch 和 gulp-watch 负责检测文件系统变化并触发构建任务。现代开发通常将两者结合使用,但选择取决于项目规模、遗留系统兼容性及对配置控制的需求。
在前端工程化中,构建工具和文件监听是基础设施的核心。本文对比 webpack、rollup、parcel、browserify 四种打包器,以及 chokidar、watchify、grunt-contrib-watch、gulp-watch 四种监听方案。我们将通过实际代码展示它们的工作方式,并明确指出哪些工具已不再适合新项目。
打包器的核心任务是将多个文件合并,处理依赖,并优化输出。
webpack 提供最强的定制能力,通过配置文件定义入口、输出和加载规则。
// webpack.config.js
module.exports = {
mode: 'production',
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: __dirname + '/dist'
},
module: {
rules: [
{ test: /\.css$/, use: ['style-loader', 'css-loader'] }
]
}
};
rollup 专注于 ES 模块,配置更简洁,适合库开发。
// rollup.config.js
export default {
input: 'src/index.js',
output: {
file: 'dist/bundle.js',
format: 'esm'
},
plugins: [
// 需要额外插件处理 CommonJS
]
};
parcel 主张零配置,通过 package.json 脚本直接运行。
// package.json
{
"scripts": {
"start": "parcel src/index.html",
"build": "parcel build src/index.html"
}
}
browserify 使用命令行或 API 将 CommonJS 模块打包,无内置配置文件的传统。
# 命令行直接打包
browserify src/main.js -o dist/bundle.js
// 或使用 API
const browserify = require('browserify');
const b = browserify('./src/main.js');
b.bundle().pipe(require('fs').createWriteStream('./dist/bundle.js'));
监听器负责检测文件变化,通知打包器重新构建。
chokidar 是纯文件监听库,不处理打包,常作为其他工具的底层依赖。
// 监听 src 目录变化
const chokidar = require('chokidar');
const watcher = chokidar.watch('src', { ignored: /node_modules/ });
watcher.on('change', path => console.log(`File ${path} changed`));
watchify 是 browserify 的监听包装器,实现增量构建。
// 结合 browserify 使用
const watchify = require('watchify');
const browserify = require('browserify');
const b = watchify(browserify('./src/main.js'));
b.on('update', () => {
b.bundle().pipe(require('fs').createWriteStream('./dist/bundle.js'));
});
grunt-contrib-watch 依赖 Grunt 任务系统,配置在 Gruntfile 中。
// Gruntfile.js
module.exports = function(grunt) {
grunt.initConfig({
watch: {
scripts: {
files: ['src/**/*.js'],
tasks: ['browserify']
}
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
};
gulp-watch 依赖 Gulp 流式系统,通常配合 gulp 任务使用。
// gulpfile.js
const gulp = require('gulp');
const watch = require('gulp-watch'); // 旧插件
gulp.task('watch', function() {
watch('src/**/*.js', function() {
gulp.start('scripts');
});
});
在前端架构演进中,部分工具已不再推荐用于新项目。
grunt-contrib-watch:Grunt 生态已停滞。新任务调度建议直接使用 npm scripts 或现代打包器的内置 watch 模式。gulp-watch:Gulp 4 已内置 gulp.watch() API,该插件不再必要。且 Gulp 本身在纯前端构建中地位下降。browserify / watchify:虽然仍可用,但缺乏对 ES 模块、Tree-shaking 和代码分割的原生支持。除非维护旧项目,否则建议迁移。现代开发倾向于使用内置监听功能的打包器,减少额外依赖。
webpack 内置监听
// webpack.config.js
module.exports = {
// ...
watch: true, // 开启监听
watchOptions: {
aggregateTimeout: 300
}
};
rollup 内置监听
# 命令行开启 watch
rollup -c --watch
parcel 内置监听
# 默认即包含热更新
parcel src/index.html
| 特性 | webpack | rollup | parcel | browserify |
|---|---|---|---|---|
| 配置难度 | 高 | 中 | 低 (零配置) | 低 |
| 主要场景 | 大型应用 | 类库/组件 | 快速原型/中小型 | 遗留 CommonJS |
| ESM 支持 | 完善 | 原生优先 | 完善 | 需插件 |
| 内置 Watch | ✅ | ✅ | ✅ | ❌ (需 watchify) |
| 特性 | chokidar | watchify | grunt-watch | gulp-watch |
|---|---|---|---|---|
| 类型 | 底层库 | 打包器插件 | 任务运行器插件 | 任务运行器插件 |
| 独立性 | 高 | 低 (依赖 browserify) | 低 (依赖 grunt) | 低 (依赖 gulp) |
| 推荐度 | ✅ (底层用) | ❌ (遗留) | ❌ (遗留) | ❌ (遗留) |
webpack 是构建复杂单页应用(SPA)的稳健选择,生态最丰富,适合需要精细控制构建流程的团队。
rollup 是发布 JavaScript 库的首选,生成的代码更干净,体积更小,适合 npm 包开发。
parcel 适合追求开发效率的场景,如内部工具、原型验证或小型站点,减少配置维护成本。
chokidar 不应直接用于业务构建,但如果你正在开发自己的 CLI 工具或构建系统,它是文件监听的标准依赖。
grunt / gulp / browserify 系列:除非维护五年前的老项目,否则不要在新架构中引入。现代打包器已内置了它们的核心功能,且性能更好。
最终结论:对于 2024 年及以后的新项目,优先选择 webpack(应用)、rollup(库)或 vite(未在此列表但值得注意)。仅在必要时使用 chokidar 作为底层依赖,避免使用独立的旧式监听插件。
选择 chokidar 如果你需要编写自定义的文件监听逻辑,或构建自己的构建工具。它是跨平台最稳定的监听库,被 webpack 和 vite 等工具内部使用,适合底层开发而非直接业务构建。
不建议在新项目中使用 gulp-watch。Gulp 4 已内置了 watch 方法,该插件是旧版本遗留物。如果你必须用 Gulp,请使用内置 API,否则建议迁移到 webpack 或 vite。
选择 browserify 如果你维护遗留的 CommonJS 项目,且不需要现代打包器的高级功能。它简单直接,但在处理 ES 模块、代码分割和性能优化方面已落后于现代工具。
不建议在新项目中使用 grunt-contrib-watch。它是 Grunt 任务运行器的插件,Grunt 生态已 largely 被 npm scripts 和现代打包器取代,仅适用于维护旧的 Grunt 构建流程。
选择 parcel 如果你希望零配置快速启动项目,或者用于原型开发。它自动处理依赖、转换代码和优化资源,适合中小型项目,但在高度定制化场景下不如 webpack 灵活。
选择 rollup 如果你主要开发 JavaScript 库或需要生成干净的 ESM 包。它的配置比 webpack 简单,生成的代码体积更小,支持 Tree-shaking,但不适合处理复杂的资源加载(如 CSS 图片)。
选择 watchify 如果你必须使用 browserify 且需要监听文件变化自动重新打包。它是 browserify 的包装器,提供了 watch 模式,但仅适用于 browserify 生态。
选择 webpack 如果你需要构建复杂的大型应用,且依赖丰富的 loader 和插件生态。它配置灵活,支持代码分割、热模块替换(HMR)和多种资源处理,适合企业级项目,但学习曲线较陡。
Minimal and efficient cross-platform file watching library
There are many reasons to prefer Chokidar to raw fs.watch / fs.watchFile in 2026:
renameatomic option
awaitWriteFinish option
Chokidar relies on the Node.js core fs module, but when using
fs.watch and fs.watchFile for watching, it normalizes the events it
receives, often checking for truth by getting file stats and/or dir contents.
The fs.watch-based implementation is the default, which
avoids polling and keeps CPU usage down. Be advised that chokidar will initiate
watchers recursively for everything within scope of the paths that have been
specified, so be judicious about not wasting system resources by watching much
more than needed. For some cases, fs.watchFile, which utilizes polling and uses more resources, is used.
Made for Brunch in 2012, it is now used in ~30 million repositories and has proven itself in production environments.
Install with npm:
npm install chokidar
Use it in your code:
import chokidar from 'chokidar';
// One-liner for current directory
chokidar.watch('.').on('all', (event, path) => {
console.log(event, path);
});
// Extended options
// ----------------
// Initialize watcher.
const watcher = chokidar.watch('file, dir, or array', {
ignored: (path, stats) => stats?.isFile() && !path.endsWith('.js'), // only watch js files
persistent: true,
});
// Something to use when events are received.
const log = console.log.bind(console);
// Add event listeners.
watcher
.on('add', (path) => log(`File ${path} has been added`))
.on('change', (path) => log(`File ${path} has been changed`))
.on('unlink', (path) => log(`File ${path} has been removed`));
// More possible events.
watcher
.on('addDir', (path) => log(`Directory ${path} has been added`))
.on('unlinkDir', (path) => log(`Directory ${path} has been removed`))
.on('error', (error) => log(`Watcher error: ${error}`))
.on('ready', () => log('Initial scan complete. Ready for changes'))
.on('raw', (event, path, details) => {
// internal
log('Raw event info:', event, path, details);
});
// 'add', 'addDir' and 'change' events also receive stat() results as second
// argument when available: https://nodejs.org/api/fs.html#fs_class_fs_stats
watcher.on('change', (path, stats) => {
if (stats) console.log(`File ${path} changed size to ${stats.size}`);
});
// Watch new files.
watcher.add('new-file');
watcher.add(['new-file-2', 'new-file-3']);
// Get list of actual paths being watched on the filesystem
let watchedPaths = watcher.getWatched();
// Un-watch some files.
await watcher.unwatch('new-file');
// Stop watching. The method is async!
await watcher.close().then(() => console.log('closed'));
// Full list of options. See below for descriptions.
// Do not use this example!
chokidar.watch('file', {
persistent: true,
// ignore .txt files
ignored: (file) => file.endsWith('.txt'),
// watch only .txt files
// ignored: (file, _stats) => _stats?.isFile() && !file.endsWith('.txt'),
awaitWriteFinish: true, // emit single event when chunked writes are completed
atomic: true, // emit proper events when "atomic writes" (mv _tmp file) are used
// The options also allow specifying custom intervals in ms
// awaitWriteFinish: {
// stabilityThreshold: 2000,
// pollInterval: 100
// },
// atomic: 100,
interval: 100,
binaryInterval: 300,
cwd: '.',
depth: 99,
followSymlinks: true,
ignoreInitial: false,
ignorePermissionErrors: false,
usePolling: false,
alwaysStat: false,
});
chokidar.watch(paths, [options])
paths (string or array of strings). Paths to files, dirs to be watched
recursively.options (object) Options object as defined below:persistent (default: true). Indicates whether the process
should continue to run as long as files are being watched.ignored function, regex, or path. Defines files/paths to be ignored.
The whole relative or absolute path is tested, not just filename. If a function with two arguments
is provided, it gets called twice per path - once with a single argument (the path), second
time with two arguments (the path and the
fs.Stats
object of that path).ignoreInitial (default: false). If set to false then add/addDir events are also emitted for matching paths while
instantiating the watching as chokidar discovers these file paths (before the ready event).followSymlinks (default: true). When false, only the
symlinks themselves will be watched for changes instead of following
the link references and bubbling events through the link's path.cwd (no default). The base directory from which watch paths are to be
derived. Paths emitted with events will be relative to this.usePolling (default: false).
Whether to use fs.watchFile (backed by polling), or fs.watch. If polling
leads to high CPU utilization, consider setting this to false. It is
typically necessary to set this to true to successfully watch files over
a network, and it may be necessary to successfully watch files in other
non-standard situations. Setting to true explicitly on MacOS overrides the
useFsEvents default. You may also set the CHOKIDAR_USEPOLLING env variable
to true (1) or false (0) in order to override this option.usePolling: true)
interval (default: 100). Interval of file system polling, in milliseconds. You may also
set the CHOKIDAR_INTERVAL env variable to override this option.binaryInterval (default: 300). Interval of file system
polling for binary files.
(see list of binary extensions)alwaysStat (default: false). If relying upon the
fs.Stats
object that may get passed with add, addDir, and change events, set
this to true to ensure it is provided even in cases where it wasn't
already available from the underlying watch events.depth (default: undefined). If set, limits how many levels of
subdirectories will be traversed.awaitWriteFinish (default: false).
By default, the add event will fire when a file first appears on disk, before
the entire file has been written. Furthermore, in some cases some change
events will be emitted while the file is being written. In some cases,
especially when watching for large files there will be a need to wait for the
write operation to finish before responding to a file creation or modification.
Setting awaitWriteFinish to true (or a truthy value) will poll file size,
holding its add and change events until the size does not change for a
configurable amount of time. The appropriate duration setting is heavily
dependent on the OS and hardware. For accurate detection this parameter should
be relatively high, making file watching much less responsive.
Use with caution.
options.awaitWriteFinish can be set to an object in order to adjust
timing params:awaitWriteFinish.stabilityThreshold (default: 2000). Amount of time in
milliseconds for a file size to remain constant before emitting its event.awaitWriteFinish.pollInterval (default: 100). File size polling interval, in milliseconds.ignorePermissionErrors (default: false). Indicates whether to watch files
that don't have read permissions if possible. If watching fails due to EPERM
or EACCES with this set to true, the errors will be suppressed silently.atomic (default: true if useFsEvents and usePolling are false).
Automatically filters out artifacts that occur when using editors that use
"atomic writes" instead of writing directly to the source file. If a file is
re-added within 100 ms of being deleted, Chokidar emits a change event
rather than unlink then add. If the default of 100 ms does not work well
for you, you can override it by setting atomic to a custom value, in
milliseconds.chokidar.watch() produces an instance of FSWatcher. Methods of FSWatcher:
.add(path / paths): Add files, directories for tracking.
Takes an array of strings or just one string..on(event, callback): Listen for an FS event.
Available events: add, addDir, change, unlink, unlinkDir, ready,
raw, error.
Additionally all is available which gets emitted with the underlying event
name and path for every event other than ready, raw, and error. raw is internal, use it carefully..unwatch(path / paths): Stop watching files or directories.
Takes an array of strings or just one string..close(): async Removes all listeners from watched files. Asynchronous, returns Promise. Use with await to ensure bugs don't happen..getWatched(): Returns an object representing all the paths on the file
system being watched by this FSWatcher instance. The object's keys are all the
directories (using absolute paths unless the cwd option was used), and the
values are arrays of the names of the items contained in each directory.Check out third party chokidar-cli, which allows to execute a command on each change, or get a stdio stream of change events.
Sometimes, Chokidar runs out of file handles, causing EMFILE and ENOSP errors:
bash: cannot set terminal process group (-1): Inappropriate ioctl for device bash: no job control in this shellError: watch /home/ ENOSPCThere are two things that can cause it.
fs module used by chokidar: let fs = require('fs'); let grfs = require('graceful-fs'); grfs.gracefulify(fs);echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p.fs.watch
usePolling: true, which will switch backend to resource-intensive fs.watchFileAll fsevents-related issues (WARN optional dep failed, fsevents is not a constructor) are solved by upgrading to v4+.
If you've used globs before and want do replicate the functionality with v4:
// v3
chok.watch('**/*.js');
chok.watch('./directory/**/*');
// v4
chok.watch('.', {
ignored: (path, stats) => stats?.isFile() && !path.endsWith('.js'), // only watch js files
});
chok.watch('./directory');
// other way
import { glob } from 'node:fs/promises';
const watcher = watch(await Array.fromAsync(glob('**/*.js')));
// unwatching
// v3
chok.unwatch('**/*.js');
// v4
chok.unwatch(await Array.fromAsync(glob('**/*.js')));
Why was chokidar named this way? What's the meaning behind it?
Chowkidar is a transliteration of a Hindi word meaning 'watchman, gatekeeper', चौकीदार. This ultimately comes from Sanskrit _ चतुष्क_ (crossway, quadrangle, consisting-of-four). This word is also used in other languages like Urdu as (چوکیدار) which is widely used in Pakistan and India.
MIT (c) Paul Miller (https://paulmillr.com), see LICENSE file.