or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-watchify

Watch mode for browserify builds with automatic recompilation when source files change

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/watchify@4.0.x

To install, run

npx @tessl/cli install tessl/npm-watchify@4.0.0

index.mddocs/

Watchify

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.

Package Information

  • Package Name: watchify
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install -g watchify (global CLI) or npm install watchify (library)

Core Imports

var watchify = require('watchify');

Basic Usage

Command Line Interface

# 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/**"

Programmatic API

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

Capabilities

Main Watchify Function

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

Default Arguments Object

Pre-configured browserify arguments for optimal caching.

/**
 * Default browserify arguments with cache and packageCache
 */
watchify.args = {
  cache: {},
  packageCache: {}
};

Enhanced Browserify Instance Methods

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

Events

The enhanced browserify instance emits additional events for monitoring build process:

File Change Events

/**
 * Emitted when files change
 * @param {string[]} ids - Array of changed file IDs
 */
b.on('update', function(ids) {
  // Rebuild bundle when files change
});

Build Metrics Events

/**
 * 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)"
});

Command Line Interface

Required Options

# Required: specify output file
--outfile=FILE, -o FILE

Standard Options

# Show verbose build information
--verbose, -v

# Display version information
--version

Advanced Options

# 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=INTERVAL

Usage Examples

Basic File Watching

var 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 build

Advanced Configuration

var 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 build

Integration with Transforms

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

Error Handling

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

Important Notes

  1. Cache Requirements: You MUST set cache: {} and packageCache: {} properties when creating the browserify instance
  2. Initial Bundle: Watchify will not emit 'update' events until you've called b.bundle() once and completely drained the stream
  3. Output File Required: When using the CLI, the -o or --outfile option is mandatory
  4. Shell Commands: The output file can be a shell command (not available on Windows) using pipes and redirects
  5. Cleanup: Call b.close() to close all file watchers when done
  6. Error Handling: Add error listeners to bundle streams to ensure errors are properly reported

Browser Compatibility

Watchify 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.