esm-hmr
v0.1.0
Published
a Hot Module Replacement (HMR) API for your ESM-based dev server.
Downloads
3
Readme
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:
- https://github.com/facebook/react/issues/16604#issuecomment-528663101
- https://github.com/JoviDeCroock/prefresh
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?
esm-hmr/client.js
- A client-side ESM-HMR runtime.esm-hmr/server.js
- A server-side ESM-HMR engine to manage connected clients.- An ESM-HMR spec to help your write your own client/server pieces. (coming soon)
Example
// Automatically injected by the dev server:
import * as $HMR$ from '/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: