esm-hmr

0.1.0 • Public • Published

ESM Hot Module Replacement (ESM-HMR) Spec

Author: Fred K. Schott (co-authors welcome!)
Status: In Progress

Hot Module Replacement (HMR) lets your browser live-update individual JavaScript modules in your application during development without triggering a full browser reload or losing the current web application state. This speeds up your development speed with faster updates on every change.

Web bundlers like Webpack, Rollup, and Parcel all implemented different, bundler-specific HMR interfaces. This makes it hard to share HMR integrations across dev environments. As a result, many framework integrations like React Fast Refresh and Preact's Prefresh need to be rewritten for every bundler that they'd like to support. See:

ESM-HMR is a standard HMR API for ESM-based dev environments. The rise of bundle-free development creates the opportunity for a common, standard HMR API built on top of the browser's native module system. ESM-HMR is built for the browser's native module system, so it can be used in any ESM-based dev environment.

Who's Using ESM-HMR?

What's in This Repo?

  1. esm-hmr/client.js - A client-side ESM-HMR runtime.
  2. esm-hmr/server.js - A server-side ESM-HMR engine to manage connected clients.
  3. An ESM-HMR spec to help your write your own client/server pieces. (coming soon)

Example

// Automatically injected by the dev server:
import * as $HMRfrom '/esm-hmr/client.js';
import.meta.hot = $HMR$.createHotContext(import.meta.url);
 
// Your module's JavaScript code:
export let foo = 1;
 
// HMR Logic:
if (import.meta.hot) {
  // Required: Mark this module as HMR-ready.
  // - Receive any module updates into the accept callback.
  // - Update the main module acordingly.
  import.meta.hot.accept(({module}) => {
    try {
      foo = module.foo;
    } catch (err) {
      // Optional: If an error occurs during update, invalidate the module.
      // This will naively trigger a full page reload.
      import.meta.hot.invalidate();
    }
  });
  // Optional: Perform any cleanup when a module is replaced.
  import.meta.hot.dispose(() => { /* ... */ });
}

Spec Details

Note: We are still fleshing this out, and this section is still under development.

Our first goal is to generalize and document Snowpack's browser-native HMR implementation for a first-round of feedback. Our second goal is to expand this spec to support Preact's Prefresh, React's Fast Reload + Error Reporting, and any features needed by other popular HMR implementations.

Prior Art

This spec wouldn't exist without the prior work of the following projects:

Readme

Keywords

none

Package Sidebar

Install

npm i esm-hmr

Weekly Downloads

1

Version

0.1.0

License

MIT

Unpacked Size

10.3 kB

Total Files

6

Last publish

Collaborators

  • fredkschott