FredKSchott / esm-hmr

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

Feature: Dependency Accept Handling #9

Closed FredKSchott closed 4 years ago

FredKSchott commented 4 years ago

Yeah, so here's a use case we've had quite often for the whitelist usage (pseudo code based on Vuex usage, but applies to Redux as well for store.replaceReducer):

// store.js
import moduleA from './modules/a'
import moduleB from './modules/b'

export const store = createStore({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

import.meta.hot.accept(['./modules/a', './modules/b'], ([newA, newB]) => {
  store.replaceModules({
    a: newA,
    b: newB
  })
})

The key here is the store is exported and used by the application. Preserving the current store.js instance is important - otherwise, you would create a new store but the app will still be using the old one. And with your current implementation, it seems a bit awkward to force rerender the app with a new store provider from the hot callback of store.js.

Originally posted by @yyx990803 in https://github.com/pikapkg/esm-hmr/issues/7#issuecomment-632898804

FredKSchott commented 4 years ago

Final implementation to match our existing accept callback structure:

import moduleA from "./modules/a.js";
import moduleB from "./modules/b.js";

export const store = createStore({
  modules: { a: moduleA, b: moduleB },
});

import.meta.hot.accept(
  ["./modules/a.js", "./modules/b.js"],
  ({ module, deps }) => {
    store.replaceModules({
      a: deps[0].default,
      b: deps[1].default,
    });
  }
);

README updated