Skip to content

Commit

Permalink
docs: add Dynamic module hot reloading example (#1744)
Browse files Browse the repository at this point in the history
Adapted from: kazupon/vue-i18n#865
  • Loading branch information
sphinxDevVic committed May 11, 2020
1 parent 124c683 commit 2fa8a7a
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions docs/guide/hot-reload.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,50 @@ if (module.hot) {
```

Checkout the [counter-hot example](https://github.com/vuejs/vuex/tree/dev/examples/counter-hot) to play with hot-reload.

## Dynamic module hot reloading

If you use modules exclusively, you can use `require.context` to load and hot reload all modules dynamically.

```js
// store.js
import Vue from 'vue'
import Vuex from 'vuex'

// Load all modules.
function loadModules() {
const context = require.context("./modules", false, /([a-z_]+)\.js$/i)

const modules = context
.keys()
.map((key) => ({ key, name: key.match(/([a-z_]+)\.js$/i)[1] }))
.reduce(
(modules, { key, name }) => ({
...modules,
[name]: context(key).default
}),
{}
)

return { context, modules }
}

const { context, modules } = loadModules()

Vue.use(Vuex)

const store = new Vuex.Store({
modules
})

if (module.hot) {
// Hot reload whenever any module changes.
module.hot.accept(context.id, () => {
const { modules } = loadModules()

store.hotUpdate({
modules
})
})
}
```

0 comments on commit 2fa8a7a

Please sign in to comment.