Skip to content

Instantly share code, notes, and snippets.

@samwightt
Created September 13, 2021 15:36
Show Gist options
  • Save samwightt/706b577c8005c5f3115bdc9ba93545c1 to your computer and use it in GitHub Desktop.
Save samwightt/706b577c8005c5f3115bdc9ba93545c1 to your computer and use it in GitHub Desktop.
export function bootstrap() {
// All of your code for setting stuff up should go in here.
// This will be run once when our module loads, and then again on every reload.
}
export function teardown() {
// This is where you delete anything you created. For instance, if you add a canvas element
// using JS, you should remove that here. Any listeners should be removed as well.
}
// This is the Vite code for HMR. First, we check to see if HMR is supported.
// If it is, import.meta.hot will be true.
if (import.meta.hot) {
// Now we use the `accept` function to listen for a new module.
// We pass it a function. Vite will call this function when we save a file and will
// pass it the new module. This is where we call our teardown function and then
// bootstrap the new module.
import.meta.hot.accept(newModule => {
// When this function is called, we've received a new module.
// First, we need to run our teardown function, to basically clear anything we did ourselves.
teardown();
// Now, we set up the new module. Because we exported our `bootstrap` function,
// we can access it on the module's object. Modules are basically objects, and the names of the
// exports are the keys. So we call newModule.bootstrap() here to set things up.
newModule.bootstrap();
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment