From f77207f804dabc2a81dbecb264f3090098968d76 Mon Sep 17 00:00:00 2001 From: 43081j <43081j@users.noreply.github.com> Date: Mon, 26 Oct 2020 17:24:17 +0000 Subject: [PATCH] add examples --- docs/docs/dev-server/plugins/hmr.md | 73 ++++++++++++++++++++++++++++- 1 file changed, 72 insertions(+), 1 deletion(-) diff --git a/docs/docs/dev-server/plugins/hmr.md b/docs/docs/dev-server/plugins/hmr.md index 1ce82a960..0ad0bbe0c 100644 --- a/docs/docs/dev-server/plugins/hmr.md +++ b/docs/docs/dev-server/plugins/hmr.md @@ -80,6 +80,14 @@ accepts updates, but will not deal with the updates. This is only really useful if your module is one which has side-effects and does not need mutating on update (i.e. has no exports). +Example: + +```ts +// will be set each time the module updates as a side-effect +window.someGlobal = 303; +import.meta.hot.accept(); +``` + ### `import.meta.hot.accept(({ module }) => { ... })` If you pass a callback to `accept`, it will be passed the updated module @@ -88,7 +96,16 @@ any time an update occurs. At this point, you should usually update any exports to be those on the new module. -### `import.meta.hot.accept(['./dep1.js', './dep2.js'], ({ deps, module }) => { ... }` +Example: + +```ts +export let foo = 808; +import.meta.hot.accept(({ module }) => { + foo = module.foo; +}); +``` + +### `import.meta.hot.accept(['./dep1.js', './dep2.js'], ({ deps, module }) => { ... })` If you specify a list of dependencies as well as a callback, your callback will be provided with the up-to-date version of each of those modules. @@ -96,17 +113,71 @@ will be provided with the up-to-date version of each of those modules. This can be useful if your updates require access to dependencies of the current module. +Example: + +```ts +import { add } from './add.js'; + +export let foo = add(10, 10); + +import.meta.hot.accept(['./add.js'], ({ deps, module }) => { + foo = deps[0].add(10, 10); +}); +``` + ### `import.meta.hot.invalidate()` Immediately invalidates the current module which will then lead to reloading the page. +Example: + +```ts +export let foo = 303; + +import.meta.hot.accept(({ module }) => { + if (!module.foo) { + import.meta.hot.invalidate(); + } else { + foo = module.foo; + } +}); +``` + ### `import.meta.hot.decline()` Notifies the server that you do not support updates, meaning any updates will result in a full page reload. +This may be useful when your module makes global changes (side effects) which +cannot be re-done. + +Example: + +```ts +doSomethingGlobal(); + +import.meta.hot.decline(); +``` + ### `import.meta.dispose(() => { ... })` Specifies a callback to be called when the current module is disposed of, before the new module is loaded and passed to `accept()`. + +Example: + +```ts +export let foo = new Server(); + +foo.start(); + +import.meta.hot.accept(({ module }) => { + foo = module.foo; + foo.start(); +}); + +import.meta.dispose(() => { + foo.stop(); +}); +```