Skip to content

Commit 91e2f7c

Browse files
authored
docs: add Dynamic module hot reloading example (#1744)
Adapted from: kazupon/vue-i18n#865
1 parent ce0c88a commit 91e2f7c

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

docs/guide/hot-reload.md

+47
Original file line numberDiff line numberDiff line change
@@ -42,3 +42,50 @@ if (module.hot) {
4242
```
4343

4444
Checkout the [counter-hot example](https://github.com/vuejs/vuex/tree/dev/examples/counter-hot) to play with hot-reload.
45+
46+
## Dynamic module hot reloading
47+
48+
If you use modules exclusively, you can use `require.context` to load and hot reload all modules dynamically.
49+
50+
```js
51+
// store.js
52+
import Vue from 'vue'
53+
import Vuex from 'vuex'
54+
55+
// Load all modules.
56+
function loadModules() {
57+
const context = require.context("./modules", false, /([a-z_]+)\.js$/i)
58+
59+
const modules = context
60+
.keys()
61+
.map((key) => ({ key, name: key.match(/([a-z_]+)\.js$/i)[1] }))
62+
.reduce(
63+
(modules, { key, name }) => ({
64+
...modules,
65+
[name]: context(key).default
66+
}),
67+
{}
68+
)
69+
70+
return { context, modules }
71+
}
72+
73+
const { context, modules } = loadModules()
74+
75+
Vue.use(Vuex)
76+
77+
const store = new Vuex.Store({
78+
modules
79+
})
80+
81+
if (module.hot) {
82+
// Hot reload whenever any module changes.
83+
module.hot.accept(context.id, () => {
84+
const { modules } = loadModules()
85+
86+
store.hotUpdate({
87+
modules
88+
})
89+
})
90+
}
91+
```

0 commit comments

Comments
 (0)