FredKSchott / esm-hmr

a Hot Module Replacement (HMR) API for your ESM-based dev server.
MIT License
412 stars 11 forks source link

How does browser swap in the new module? #24

Open marialovesbeans opened 3 years ago

marialovesbeans commented 3 years ago

Hey guys, does anyone understand how ES Module's HMR works under-the-hood (for example in Vite or React Fast Refresh)? i.e. How is it able to swap out a modified module at runtime?

Usually, every time you change a module, browser will refetch that module via HTTP.

But after that, how does the browser replace the old module, and have the new code take into effect?

The only thing I found is https://itnext.io/hot-reloading-native-es2015-modules-dc54cd8cca01, is this the solution we're taking?

lxsmnsyc commented 3 years ago

https://github.com/snowpackjs/esm-hmr/blob/152fffe555e9281822553b495edbc95ccb6a41b2/src/client.ts#L131-L137

It uses module versioning and dynamic imports to "reload" modules without deleting the module cache. The loaded content is then passed to import.meta.hot.accept for consumption.

Also, commenting this for my own future reference