Watch mode for browserify builds with automatic recompilation when source files change
—
Watchify is a development tool that provides watch mode functionality for browserify builds, enabling automatic recompilation of JavaScript bundles when source files change. It offers both command-line and programmatic APIs with features like configurable delay timing, file watching patterns, and detailed verbose output showing build times and file sizes.
npm install -g watchify (global CLI) or npm install watchify (library)var watchify = require('watchify');# Basic usage with required output file
watchify main.js -o static/bundle.js
# With verbose output showing build stats
watchify main.js -o static/bundle.js -v
# With custom delay and ignore patterns
watchify main.js -o bundle.js --delay 200 --ignore-watch "**/node_modules/**"var browserify = require('browserify');
var watchify = require('watchify');
var fs = require('fs');
// Create browserify instance with required cache options
var b = browserify({
entries: ['src/main.js'],
cache: {},
packageCache: {},
plugin: [watchify]
});
// Handle file changes
b.on('update', bundle);
bundle();
function bundle() {
b.bundle()
.on('error', console.error)
.pipe(fs.createWriteStream('bundle.js'));
}Creates a watching browserify instance that automatically rebuilds when source files change.
/**
* Creates a watching browserify instance that auto-rebuilds on file changes
* @param {Object} b - browserify instance (required)
* @param {Object} opts - options object (optional)
* @returns {Object} Enhanced browserify instance with watching capabilities
*/
function watchify(b, opts);Options:
interface WatchifyOptions {
/** Wait time in milliseconds before emitting 'update' event after file changes */
delay?: number; // default: 100
/** File patterns to ignore when watching. If true, defaults to '**/node_modules/**' */
ignoreWatch?: string | string[] | boolean | Function;
/** Enable polling mode. If true, uses 100ms interval. If number, uses that as interval */
poll?: boolean | number;
}Pre-configured browserify arguments for optimal caching.
/**
* Default browserify arguments with cache and packageCache
*/
watchify.args = {
cache: {},
packageCache: {}
};When you pass a browserify instance to watchify, it gains additional methods:
/**
* Close all file watchers
* @returns {undefined}
*/
b.close();
/**
* Internal watcher creation method (advanced usage)
* @param {string} file - File path to watch
* @param {Object} opts - Chokidar watcher options
* @returns {Object} Chokidar watcher instance
*/
b._watcher(file, opts);The enhanced browserify instance emits additional events for monitoring build process:
/**
* Emitted when files change
* @param {string[]} ids - Array of changed file IDs
*/
b.on('update', function(ids) {
// Rebuild bundle when files change
});/**
* Emitted with number of bytes in generated bundle
* @param {number} bytes - Bundle size in bytes
*/
b.on('bytes', function(bytes) {
console.log('Bundle size:', bytes, 'bytes');
});
/**
* Emitted with time taken to build bundle
* @param {number} time - Build time in milliseconds
*/
b.on('time', function(time) {
console.log('Build time:', time, 'ms');
});
/**
* Emitted with formatted log message about build stats
* @param {string} msg - Formatted message with bytes and time
*/
b.on('log', function(msg) {
console.log(msg); // "X bytes written (Y seconds)"
});# Required: specify output file
--outfile=FILE, -o FILE# Show verbose build information
--verbose, -v
# Display version information
--version# Wait time before emitting update event (default: 100ms)
--delay=MILLISECONDS
# Ignore file patterns when watching (default: false)
--ignore-watch=GLOB, --iw GLOB
# Use polling instead of native file watching (default: false)
--poll=INTERVALvar browserify = require('browserify');
var watchify = require('watchify');
var b = browserify({
entries: ['app.js'],
cache: {},
packageCache: {}
});
var w = watchify(b);
w.on('update', function(ids) {
console.log('Files changed:', ids);
bundle();
});
function bundle() {
w.bundle()
.pipe(process.stdout);
}
bundle(); // Initial buildvar browserify = require('browserify');
var watchify = require('watchify');
var b = browserify({
entries: ['src/main.js'],
cache: {},
packageCache: {}
});
var w = watchify(b, {
delay: 200,
ignoreWatch: ['**/node_modules/**', '**/test/**'],
poll: 1000 // Use 1 second polling
});
w.on('update', rebuild);
w.on('bytes', function(bytes) {
console.log('Bundle:', bytes, 'bytes');
});
w.on('time', function(time) {
console.log('Built in:', time, 'ms');
});
function rebuild() {
w.bundle()
.on('error', function(err) {
console.error('Build error:', err.message);
})
.pipe(require('fs').createWriteStream('dist/bundle.js'));
}
rebuild(); // Initial buildFor custom browserify transforms that add files to the bundle:
// In your transform
module.exports = function(file) {
return through(function(buf, enc, next) {
// Inform watchify about additional files to watch
this.emit('file', '/absolute/path/to/dependency.js');
next();
});
};var b = browserify({ cache: {}, packageCache: {} });
var w = watchify(b);
w.on('update', bundle);
function bundle() {
var stream = w.bundle();
stream.on('error', function(err) {
console.error('Browserify error:', err.message);
});
stream.pipe(require('fs').createWriteStream('output.js'));
}
bundle();cache: {} and packageCache: {} properties when creating the browserify instanceb.bundle() once and completely drained the stream-o or --outfile option is mandatoryb.close() to close all file watchers when doneWatchify is a Node.js development tool and is not intended to run in browsers. It's used during development to watch and rebuild browserify bundles that will eventually run in browsers.
Install with Tessl CLI
npx tessl i tessl/npm-watchify