Watchify Middleware

1.9.1 · maintenance · verified Sun Apr 19

watchify-middleware is a lightweight HTTP middleware designed to enhance the development experience when working with Watchify and Browserify. It prevents stale or empty bundles from being served by suspending the server response until the bundle is ready. The middleware, currently at version 1.9.1 (last published in 2017), differentiates itself by removing the default 600ms rebuild delay common in Watchify, offering immediate feedback, and providing an optional browser-based error handler. It exposes timing information via a 'log' event and facilitates seamless integration into Node.js HTTP servers or frameworks like Express, making it ideal for rapid iteration cycles during web development. Its release cadence has been infrequent, with no major updates since its last stable release, positioning it as a mature, maintenance-mode utility.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart sets up a basic HTTP server that serves an HTML page with a 'bundle.js' script. The script is generated by Browserify and hot-reloaded by watchify-middleware, demonstrating how to integrate the middleware to serve continuously updated JavaScript bundles.

const http = require('http');
const browserify = require('browserify');
const watchifyMiddleware = require('watchify-middleware');
const defaultIndex = require('simple-html-index');

const staticUrl = 'bundle.js';
const appEntry = 'app.js';

// Create a dummy app.js for demonstration
require('fs').writeFileSync(appEntry, 'console.log("Hello from app.js!");');

const bundler = browserify(appEntry, {
  cache: {},
  packageCache: {},
  basedir: __dirname,
  plugin: [require('watchify')] // Crucial for watchify integration
});

const watchifyInstance = watchifyMiddleware(bundler, {
  errorHandler: true // Use default browser error handler
});

const server = http.createServer(function (req, res) {
  if (req.url === '/') {
    defaultIndex({ entry: staticUrl }).pipe(res);
  } else if (req.url === '/' + staticUrl) {
    watchifyInstance(req, res);
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Not Found');
  }
});

server.listen(8000, 'localhost', function () {
  console.log('Watching and serving http://localhost:8000/');
  console.log(`Try changing ${appEntry} and refreshing the browser.`);
});

view raw JSON →