or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-webpack-livereload-plugin

Webpack plugin that enables live reload functionality for web development by integrating with webpack's build pipeline

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/webpack-livereload-plugin@2.3.x

To install, run

npx @tessl/cli install tessl/npm-webpack-livereload-plugin@2.3.0

index.mddocs/

Webpack LiveReload Plugin

A webpack plugin that enables live reload functionality during development by integrating with webpack's build pipeline. It automatically refreshes web pages when files change, offering an alternative to webpack-dev-server for cases where assets need to be served by an application server rather than webpack's dev server.

Package Information

  • Package Name: webpack-livereload-plugin
  • Package Type: npm
  • Language: JavaScript (Node.js)
  • Installation: npm install --save-dev webpack-livereload-plugin

Core Imports

const LiveReloadPlugin = require('webpack-livereload-plugin');

For ES modules:

import LiveReloadPlugin from 'webpack-livereload-plugin';

Basic Usage

// webpack.config.js
const LiveReloadPlugin = require('webpack-livereload-plugin');

module.exports = {
  // webpack configuration
  plugins: [
    new LiveReloadPlugin({
      port: 35729,
      hostname: 'localhost'
    })
  ]
};

Add the LiveReload script to your HTML:

<script src="http://localhost:35729/livereload.js"></script>

Architecture

The plugin integrates with webpack's plugin system using several key hooks:

  • Server Management: Creates and manages a LiveReload server using the tiny-lr library
  • File Watching: Hooks into webpack's compilation lifecycle to detect file changes
  • Change Detection: Uses compilation hashes and optional source hashing to prevent unnecessary reloads
  • Script Injection: Optionally injects LiveReload client script into webpack bundles

Capabilities

LiveReload Plugin Constructor

Creates a new LiveReload plugin instance with optional configuration.

/**
 * Creates a new LiveReload plugin instance
 * @param {LiveReloadOptions} options - Configuration options
 */
function LiveReloadPlugin(options);

interface LiveReloadOptions {
  /** Port for the LiveReload server (default: 35729, 0 for auto-find) */
  port?: number;
  /** RegExp or array of anymatch patterns for files to ignore */
  ignore?: RegExp | Array<string | RegExp> | null;
  /** Suppress console output (default: false) */
  quiet?: boolean;
  /** Use source hash to prevent unnecessary reloads (default: false) */
  useSourceHash?: boolean;
  /** Delay in milliseconds before triggering reload (default: 0) */
  delay?: number;
  /** Protocol for script tag URLs (default: detected from page) */
  protocol?: string;
  /** Hostname for script tag URLs (default: '" + location.hostname + "') */
  hostname?: string;
  /** Automatically append script tag to HTML (default: false) */
  appendScriptTag?: boolean;
  /** HTTPS key file content or path (passed to tiny-lr) */
  key?: string;
  /** HTTPS certificate file content or path (passed to tiny-lr) */
  cert?: string;
  /** HTTPS PFX file content or path (passed to tiny-lr) */
  pfx?: string;
}

Usage Examples:

// Basic setup
const plugin = new LiveReloadPlugin();

// Custom port and hostname
const plugin = new LiveReloadPlugin({
  port: 1337,
  hostname: '10.0.2.2'
});

// Ignore CSS files and use source hashing
const plugin = new LiveReloadPlugin({
  ignore: /\.css$/,
  useSourceHash: true,
  delay: 20
});

// Multiple ignore patterns
const plugin = new LiveReloadPlugin({
  ignore: [/\.map$/, /\.json$/]
});

// Auto-append script tag
const plugin = new LiveReloadPlugin({
  appendScriptTag: true
});

// HTTPS setup
const plugin = new LiveReloadPlugin({
  protocol: 'https',
  key: fs.readFileSync('path/to/key.pem'),
  cert: fs.readFileSync('path/to/cert.pem')
});

// Comprehensive example with multiple features
const plugin = new LiveReloadPlugin({
  port: 0,                          // Auto-find available port
  hostname: '192.168.1.100',        // Custom hostname for network access
  quiet: false,                     // Show server startup message
  useSourceHash: true,              // Prevent unnecessary reloads
  delay: 100,                       // Small delay to batch rapid changes
  ignore: [                         // Ignore multiple file types
    /\.map$/,                       // Source maps
    /\.json$/,                      // JSON files
    /node_modules/                  // Dependencies
  ],
  appendScriptTag: true            // Auto-inject script into HTML
});

Server Management

Controls the LiveReload server lifecycle.

/**
 * Start the LiveReload server
 * @param {Object | null} watching - Webpack watching instance (unused)
 * @param {Function} callback - Called when server starts or fails
 */
start(watching, callback);

/**
 * Check if the LiveReload server is running
 * @returns {boolean} True if server is running
 */
get isRunning();

Compilation Integration

Handles webpack compilation events and change detection.

/**
 * Handle webpack compilation completion
 * @param {Object} stats - Webpack compilation stats
 */
done(stats);

/**
 * Handle webpack compilation failure
 */
failed();

/**
 * Apply the plugin to webpack compiler (webpack plugin interface)
 * @param {Object} compiler - Webpack compiler instance
 */
apply(compiler);

/**
 * Hook into webpack compilation for script injection (internal method)
 * @param {Object} compilation - Webpack compilation instance
 */
applyCompilation(compilation);

Script Generation

Generates JavaScript code for LiveReload client integration.

/**
 * Generate JavaScript code for auto-loading LiveReload client
 * @returns {string} JavaScript code to inject
 */
autoloadJs();

/**
 * Optionally prepend LiveReload script to source code
 * @param {string} source - Original JavaScript source
 * @returns {string} Modified or original source
 */
scriptTag(source);

Properties

Runtime properties accessible on plugin instances.

interface LiveReloadPlugin {
  /** Current port being used by the server */
  port: number;
  /** Default port used when no port is specified (35729) */
  readonly defaultPort: number;
  /** File ignore patterns */
  ignore: RegExp | Array<string | RegExp> | null;
  /** Whether console output is suppressed */
  quiet: boolean;
  /** Whether source hashing is enabled */
  useSourceHash: boolean;
  /** Reload delay in milliseconds */
  delay: number;
  /** Protocol string for script URLs */
  protocol: string;
  /** Hostname for script URLs (default: '" + location.hostname + "') */
  hostname: string;
  /** Whether the LiveReload server is running (getter) */
  readonly isRunning: boolean;
  /** Random hex string for unique instance identification */
  readonly instanceId: string;
  /** Last compilation hash for change detection (internal) */
  readonly lastHash: string | null;
  /** Array of last child compilation hashes (internal) */
  readonly lastChildHashes: string[];
  /** Storage for source file hashes when useSourceHash is enabled (internal) */
  readonly sourceHashs: Record<string, string>;
  /** Active tiny-lr server instance (internal) */
  readonly server: TinyLRServer | null;
  /** Webpack compiler instance (internal) */
  readonly compiler: Object | null;
}

Error Handling

The plugin handles common error scenarios:

  • Port conflicts: Automatically searches for available ports when port: 0
  • Server errors: Logs errors and continues operation when server fails to start
  • File filtering: Safely handles invalid ignore patterns through anymatch library

Common Error Messages:

// Port in use
"Live Reload disabled: EADDRINUSE"

// Server start failure
"Live Reload disabled: [error message]"

Types

interface WebpackCompilationStats {
  compilation: {
    /** Compilation hash for change detection */
    hash: string;
    /** Child compilation hashes */
    children: Array<{ hash: string }>;
    /** Compilation assets with emission status */
    assets: {
      [filename: string]: {
        /** Whether the asset was emitted in this compilation */
        emitted: boolean;
        /** Function to get asset source (when useSourceHash is enabled) */
        source?: () => string;
      }
    };
  };
}

interface TinyLRServer {
  /** Notify connected clients of file changes */
  notifyClients(files: string[]): void;
  /** Start listening on specified port */
  listen(port: number, callback: (error?: Error) => void): void;
  /** Close the server */
  close(): void;
}