FredKSchott / esm-hmr

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

Proposal: Call dispose() before accept() #8

Closed FredKSchott closed 4 years ago

FredKSchott commented 4 years ago

From @rixo in https://github.com/pikapkg/snowpack/pull/331

I think the dispose handler should be called before the accept handler.

Since your accept handler is static, I think it's all the more important to implement a way to pass data from the last version of the module to the next. I strongly recommend that you implement Webpack's dispose data pattern for that.

// preserve existing value or create it if first run
const value = import.meta.hot && import.meta.hot.data.value || []

export const push = (...args) => value.push(...args)

// dispose handler is passed the data object to be mutated before running the new module
import.meta.hot.dispose(data => {
  data.value = value
})

// I'm hot update able!
import.meta.hot.accept()