Hot Reloading

Vuex supports hot-reloading mutations, modules, actions and getters during development, using webpack’s Hot Module Replacement API. You can also use it in Browserify with the browserify-hmr plugin.

For mutations and modules, you need to use the store.hotUpdate() API method:

  1. // store.js
  2. import { createStore } from 'vuex'
  3. import mutations from './mutations'
  4. import moduleA from './modules/a'
  5. const state = { ... }
  6. const store = createStore({
  7. state,
  8. mutations,
  9. modules: {
  10. a: moduleA
  11. }
  12. })
  13. if (module.hot) {
  14. // accept actions and mutations as hot modules
  15. module.hot.accept(['./mutations', './modules/a'], () => {
  16. // require the updated modules
  17. // have to add .default here due to babel 6 module output
  18. const newMutations = require('./mutations').default
  19. const newModuleA = require('./modules/a').default
  20. // swap in the new modules and mutations
  21. store.hotUpdate({
  22. mutations: newMutations,
  23. modules: {
  24. a: newModuleA
  25. }
  26. })
  27. })
  28. }

Checkout the counter-hot example 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.

  1. // store.js
  2. import { createStore } from 'vuex'
  3. // Load all modules.
  4. function loadModules() {
  5. const context = require.context("./modules", false, /([a-z_]+)\.js$/i)
  6. const modules = context
  7. .keys()
  8. .map((key) => ({ key, name: key.match(/([a-z_]+)\.js$/i)[1] }))
  9. .reduce(
  10. (modules, { key, name }) => ({
  11. ...modules,
  12. [name]: context(key).default
  13. }),
  14. {}
  15. )
  16. return { context, modules }
  17. }
  18. const { context, modules } = loadModules()
  19. const store = createStore({
  20. modules
  21. })
  22. if (module.hot) {
  23. // Hot reload whenever any module changes.
  24. module.hot.accept(context.id, () => {
  25. const { modules } = loadModules()
  26. store.hotUpdate({
  27. modules
  28. })
  29. })
  30. }