Convert Figma logo to code with AI

webpack-contrib logowebpack-hot-middleware

Webpack hot reloading you can attach to your own server

2,337
297
2,337
73

Top Related Projects

Serves a webpack app. Updates the browser on changes. Documentation https://webpack.js.org/configuration/dev-server/.

Set up a modern web app by running one command.

124,777

The React Framework

67,112

Next generation frontend tooling. It's fast!

19,480

ESM-powered frontend build tool. Instant, lightweight, unbundled development. ✌️

43,380

The zero configuration build tool for the web. 📦🚀

Quick Overview

The webpack-hot-middleware is a Webpack middleware that allows for hot reloading of a web application during development. It provides a way to quickly update the browser when changes are made to the code, without the need for a full page refresh.

Pros

  • Instant Updates: The middleware enables instant updates to the browser, providing a seamless development experience.
  • Reduced Overhead: By only updating the changed modules, it reduces the overhead and improves the overall performance of the development workflow.
  • Compatibility: The middleware is compatible with various Webpack configurations and can be easily integrated into existing projects.
  • Customization: The middleware offers a range of configuration options, allowing developers to tailor its behavior to their specific needs.

Cons

  • Complexity: Integrating the middleware into a project may require some additional setup and configuration, which can add complexity to the development process.
  • Dependency on Webpack: The middleware is tightly coupled with Webpack, which means that developers who are not using Webpack may not be able to benefit from its features.
  • Potential Compatibility Issues: The middleware may not work seamlessly with all Webpack versions or configurations, which can lead to compatibility issues.
  • Limited Scope: The middleware is primarily focused on hot reloading and may not provide the full range of features that some developers might expect from a development tool.

Code Examples

Here are a few examples of how to use the webpack-hot-middleware in a Webpack-based project:

  1. Configuring the Middleware:
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');

const compiler = webpack(webpackConfig);

app.use(webpackDevMiddleware(compiler, {
  publicPath: webpackConfig.output.publicPath
}));

app.use(webpackHotMiddleware(compiler));
  1. Enabling Hot Module Replacement (HMR):
if (module.hot) {
  module.hot.accept('./path/to/module', () => {
    // Handle the updated module
    console.log('Module updated:', './path/to/module');
  });
}
  1. Customizing the Middleware:
app.use(webpackHotMiddleware(compiler, {
  log: console.log,
  path: '/__webpack_hmr',
  heartbeat: 10 * 1000
}));
  1. Handling Errors:
app.use(webpackHotMiddleware(compiler, {
  log: (msg) => {
    if (msg.indexOf('[HMR]') !== -1) {
      console.log(msg);
    }
  }
}));

Getting Started

To get started with the webpack-hot-middleware, follow these steps:

  1. Install the package using npm or yarn:
npm install --save-dev webpack-hot-middleware
  1. Configure the middleware in your Webpack configuration file:
const webpack = require('webpack');

module.exports = {
  // Your Webpack configuration
  entry: [
    'webpack-hot-middleware/client',
    './src/index.js'
  ],
  plugins: [
    new webpack.HotModuleReplacementPlugin()
  ]
};
  1. Integrate the middleware into your server-side code (e.g., Express, Koa, or any other Node.js server):
const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');

const app = express();
const compiler = webpack(webpackConfig);

app.use(webpackDevMiddleware(compiler, {
  publicPath: webpackConfig.output.publicPath
}));

app.use(webpackHotMiddleware(compiler));

app.listen(3000, () => {
  console.log('Server started on port 3000');
});
  1. Start your development server and enjoy the benefits of hot reloading!

Competitor Comparisons

Serves a webpack app. Updates the browser on changes. Documentation https://webpack.js.org/configuration/dev-server/.

Pros of webpack-dev-server

  • Provides a full-featured development server with live reloading
  • Offers more configuration options and flexibility
  • Integrates seamlessly with webpack's ecosystem

Cons of webpack-dev-server

  • Requires more setup and configuration
  • Can be overkill for smaller projects or simple use cases
  • May have a steeper learning curve for beginners

Code Comparison

webpack-dev-server configuration:

module.exports = {
  devServer: {
    contentBase: './dist',
    hot: true,
    port: 8080
  }
};

webpack-hot-middleware usage:

app.use(webpackDevMiddleware(compiler, {
  publicPath: config.output.publicPath
}));
app.use(webpackHotMiddleware(compiler));

Summary

webpack-dev-server is a more comprehensive solution for development environments, offering a full-featured server with extensive configuration options. It's ideal for larger projects or those requiring advanced features.

webpack-hot-middleware is a lightweight alternative, focusing specifically on hot module replacement. It's easier to set up and integrate into existing Express.js applications but lacks some of the additional features provided by webpack-dev-server.

Choose webpack-dev-server for a complete development server solution with broader capabilities, or opt for webpack-hot-middleware if you need a simpler hot reloading setup or want to integrate with an existing Express.js server.

Set up a modern web app by running one command.

Pros of create-react-app

  • Provides a complete, pre-configured development environment for React applications
  • Abstracts away complex build configurations, allowing developers to focus on writing code
  • Includes built-in optimizations for production builds

Cons of create-react-app

  • Less flexible than webpack-hot-middleware for custom configurations
  • Can be challenging to eject and modify the underlying build system
  • May include unnecessary dependencies for simpler projects

Code Comparison

webpack-hot-middleware:

app.use(require('webpack-dev-middleware')(compiler, {
  publicPath: config.output.publicPath
}));

app.use(require('webpack-hot-middleware')(compiler));

create-react-app:

// No configuration needed, just run:
npx create-react-app my-app
cd my-app
npm start

Key Differences

  • webpack-hot-middleware is a specific middleware for enabling Hot Module Replacement (HMR) in webpack-based projects
  • create-react-app is a comprehensive toolchain for creating React applications with a pre-configured development environment
  • webpack-hot-middleware requires manual setup and integration with an existing webpack configuration
  • create-react-app provides a complete, opinionated setup out of the box, hiding webpack configuration details from the developer

Use Cases

  • Use webpack-hot-middleware when you need fine-grained control over your webpack configuration and HMR setup
  • Use create-react-app when you want to quickly bootstrap a new React project with minimal configuration and a standardized build process
124,777

The React Framework

Pros of Next.js

  • Full-featured React framework with built-in routing, server-side rendering, and API routes
  • Automatic code splitting and optimized performance out of the box
  • Extensive ecosystem and community support

Cons of Next.js

  • Steeper learning curve for developers new to React or server-side rendering
  • Less flexibility in configuration compared to webpack-based setups
  • Potential overhead for simple projects that don't require all features

Code Comparison

Next.js:

// pages/index.js
export default function Home() {
  return <h1>Welcome to Next.js!</h1>
}

webpack-hot-middleware:

// server.js
app.use(require('webpack-dev-middleware')(compiler, {
  publicPath: config.output.publicPath,
}));
app.use(require('webpack-hot-middleware')(compiler));

Key Differences

  • Next.js is a comprehensive framework, while webpack-hot-middleware is a specific tool for hot module replacement
  • Next.js provides a more opinionated structure and built-in features, whereas webpack-hot-middleware offers more flexibility within existing webpack setups
  • Next.js focuses on React applications, while webpack-hot-middleware can be used with various JavaScript frameworks

Use Cases

  • Choose Next.js for full-stack React applications with server-side rendering requirements
  • Opt for webpack-hot-middleware when you need hot reloading in a custom webpack configuration or non-React project
67,112

Next generation frontend tooling. It's fast!

Pros of Vite

  • Faster development server startup and hot module replacement (HMR)
  • Native ES modules support, reducing bundle size and improving performance
  • Built-in support for TypeScript, JSX, and CSS pre-processors

Cons of Vite

  • Less mature ecosystem compared to webpack
  • Limited plugin availability and compatibility with existing webpack plugins
  • Potential challenges when migrating large, complex projects from webpack

Code Comparison

Vite configuration:

// vite.config.js
export default {
  plugins: [react()],
  server: {
    hmr: true
  }
}

webpack-hot-middleware configuration:

// webpack.config.js
module.exports = {
  entry: ['webpack-hot-middleware/client', './src/index.js'],
  plugins: [new webpack.HotModuleReplacementPlugin()]
};

Summary

Vite offers faster development experience and modern features, while webpack-hot-middleware provides a more established ecosystem with broader plugin support. Vite's configuration is generally simpler, but migration from webpack may require additional effort for complex projects. The choice between the two depends on project requirements, team familiarity, and desired development workflow.

19,480

ESM-powered frontend build tool. Instant, lightweight, unbundled development. ✌️

Pros of Snowpack

  • Faster development experience with no-bundle approach
  • Built-in support for modern web technologies (ES modules, import maps)
  • Simpler configuration and setup process

Cons of Snowpack

  • Less mature ecosystem compared to webpack
  • May require additional plugins for advanced optimizations
  • Limited support for older browsers without proper configuration

Code Comparison

Snowpack (simple configuration):

// snowpack.config.js
module.exports = {
  mount: {
    public: '/',
    src: '/dist',
  },
};

webpack-hot-middleware (basic setup):

// webpack.config.js
module.exports = {
  entry: ['webpack-hot-middleware/client', './src/index.js'],
  plugins: [new webpack.HotModuleReplacementPlugin()],
};

Snowpack focuses on a no-bundle approach during development, providing faster build times and a simpler configuration. It leverages modern web technologies out of the box, making it easier to work with ES modules and import maps.

webpack-hot-middleware, being part of the webpack ecosystem, offers a more mature and battle-tested solution for hot module replacement. It provides greater flexibility and a wider range of optimization options, but may require more complex configuration.

Snowpack's simplicity makes it attractive for smaller projects or those focusing on modern web development, while webpack-hot-middleware remains a solid choice for larger, more complex applications that require extensive customization and optimization.

43,380

The zero configuration build tool for the web. 📦🚀

Pros of Parcel

  • Zero configuration required, making it easier to set up and use
  • Faster build times due to its built-in caching and multi-core processing
  • Supports a wide range of file types out of the box, including JavaScript, CSS, HTML, and more

Cons of Parcel

  • Less flexibility and customization options compared to Webpack ecosystem
  • Smaller community and ecosystem, which may result in fewer plugins and resources
  • May not be suitable for complex projects that require fine-grained control over the build process

Code Comparison

Webpack Hot Middleware setup:

const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const config = require('./webpack.config.js');
const compiler = webpack(config);

Parcel setup:

const Bundler = require('parcel-bundler');
const entryFiles = './src/index.html';
const bundler = new Bundler(entryFiles);

Parcel requires significantly less configuration and setup compared to Webpack Hot Middleware. While Webpack Hot Middleware offers more control and customization, Parcel provides a simpler and faster development experience out of the box. The choice between the two depends on project requirements, complexity, and developer preferences.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Webpack Hot Middleware

Webpack hot reloading using only webpack-dev-middleware. This allows you to add hot reloading into an existing server without webpack-dev-server.

This module is only concerned with the mechanisms to connect a browser client to a webpack server & receive updates. It will subscribe to changes from the server and execute those changes using webpack's HMR API. Actually making your application capable of using hot reloading to make seamless changes is out of scope, and usually handled by another library.

If you're using React then some common options are react-transform-hmr and react-hot-loader.

npm version CircleCIcodecovMIT Licensed

Installation & Usage

See example/ for an example of usage.

First, install the npm module.

npm install --save-dev webpack-hot-middleware

Next, enable hot reloading in your webpack config:

  1. Add the following plugins to the plugins array:

    plugins: [
        new webpack.HotModuleReplacementPlugin(),
    ]
    

    Occurence ensures consistent build hashes, hot module replacement is somewhat self-explanatory, no errors is used to handle errors more cleanly.

  2. Add 'webpack-hot-middleware/client' into an array of the entry object. For example:

    entry: {
        main: ['webpack-hot-middleware/client', './src/main.js']
    }
    

    This connects to the server to receive notifications when the bundle rebuilds and then updates your client bundle accordingly.

Now add the middleware into your server:

  1. Add webpack-dev-middleware the usual way

    var webpack = require('webpack');
    var webpackConfig = require('./webpack.config');
    var compiler = webpack(webpackConfig);
    
    app.use(require("webpack-dev-middleware")(compiler, {
        /* Options */
    }));
    
  2. Add webpack-hot-middleware attached to the same compiler instance

    app.use(require("webpack-hot-middleware")(compiler));
    

And you're all set!

Changelog

2.0.0

Breaking Change

As of version 2.0.0, all client functionality has been rolled into this module. This means that you should remove any reference to webpack/hot/dev-server or webpack/hot/only-dev-server from your webpack config. Instead, use the reload config option to control this behaviour.

This was done to allow full control over the client receiving updates, which is now able to output full module names in the console when applying changes.

Documentation

More to come soon, you'll have to mostly rely on the example for now.

Config

Client

Configuration options can be passed to the client by adding querystring parameters to the path in the webpack config.

'webpack-hot-middleware/client?path=/__what&timeout=2000&overlay=false'
  • path - The path which the middleware is serving the event stream on
  • name - Bundle name, specifically for multi-compiler mode
  • timeout - The time to wait after a disconnection before attempting to reconnect
  • overlay - Set to false to disable the DOM-based client-side overlay.
  • reload - Set to true to auto-reload the page when webpack gets stuck.
  • noInfo - Set to true to disable informational console logging.
  • quiet - Set to true to disable all console logging.
  • dynamicPublicPath - Set to true to use webpack publicPath as prefix of path. (We can set __webpack_public_path__ dynamically at runtime in the entry point, see note of output.publicPath)
  • autoConnect - Set to false to use to prevent a connection being automatically opened from the client to the webpack back-end - ideal if you need to modify the options using the setOptionsAndConnect function
  • ansiColors - An object to customize the client overlay colors as mentioned in the ansi-html-community package.
  • overlayStyles - An object to let you override or add new inline styles to the client overlay div.
  • overlayWarnings - Set to true to enable client overlay on warnings in addition to errors.
  • statsOptions - An object to customize stats options.

Note: Since the ansiColors and overlayStyles options are passed via query string, you'll need to uri encode your stringified options like below:

var ansiColors = {
  red: '00FF00' // note the lack of "#"
};
var overlayStyles = {
  color: '#FF0000' // note the inclusion of "#" (these options would be the equivalent of div.style[option] = value)
};
var hotMiddlewareScript = 'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=true&ansiColors=' + encodeURIComponent(JSON.stringify(ansiColors)) + '&overlayStyles=' + encodeURIComponent(JSON.stringify(overlayStyles));

Middleware

Configuration options can be passed to the middleware by passing a second argument.

app.use(require("webpack-hot-middleware")(compiler, {
    log: false,
    path: "/__what",
    heartbeat: 2000
}));
  • log - A function used to log lines, pass false to disable. Defaults to console.log
  • path - The path which the middleware will serve the event stream on, must match the client setting
  • heartbeat - How often to send heartbeat updates to the client to keep the connection alive. Should be less than the client's timeout setting - usually set to half its value.

How it Works

The middleware installs itself as a webpack plugin, and listens for compiler events.

Each connected client gets a Server Sent Events connection, the server will publish notifications to connected clients on compiler events.

When the client receives a message, it will check to see if the local code is up to date. If it isn't up to date, it will trigger webpack hot module reloading.

Multi-compiler mode

If you're using multi-compiler mode (exporting an array of config in webpack.config.js), set name parameters to make sure bundles don't process each other's updates. For example:

// webpack.config.js
module.exports = [
    {
        name: 'mobile',
        entry: {
            vendor: 'vendor.js',
            main: ['webpack-hot-middleware/client?name=mobile', 'mobile.js']
        }
    },
    {
        name: 'desktop',
        entry: {
            vendor: 'vendor.js',
            main: ['webpack-hot-middleware/client?name=desktop', 'desktop.js']
        }
    }
]

Other Frameworks

Hapi

Use the hapi-webpack-plugin.

Koa

koa-webpack-middleware wraps this module for use with Koa 1.x

koa-webpack can be used for Koa 2.x

Troubleshooting

Use on browsers without EventSource

If you want to use this module with browsers that don't support eventsource, you'll need to use a polyfill. See issue #11

Not receiving updates in client when using Gzip

This is because gzip generally buffers the response, but the Server Sent Events event-stream expects to be able to send data to the client immediately. You should make sure gzipping isn't being applied to the event-stream. See issue #10.

Use with auto-restarting servers

This module expects to remain running while you make changes to your webpack bundle, if you use a process manager like nodemon then you will likely see very slow changes on the client side. If you want to reload the server component, either use a separate process, or find a way to reload your server routes without restarting the whole process. See https://github.com/glenjamin/ultimate-hot-reloading-example for an example of one way to do this.

Use with multiple entry points in webpack

If you want to use multiple entry points in your webpack config you need to include the hot middleware client in each entry point. This ensures that each entry point file knows how to handle hot updates. See the examples folder README for an example.

entry: {
    vendor: ['jquery', 'webpack-hot-middleware/client'],
    index: ['./src/index', 'webpack-hot-middleware/client']
}

License

See LICENSE file.

NPM DownloadsLast 30 Days