Search code examples
vue.jswebpackvue-cli-3webpack-hmr

Changes on imported JS files with Vue CLI project trigger page reload


When I make changes to any function .js file under ./src/fn hot reload is not working and triggers a page reload.

I have been trying to make configure vue.config.js to include the directory to HMR correctly. Also I tried using my custom helpers as a Vue.use(myPlugin).

/* functions.js (just a part of it) */
export const Functions = {
  game: {
    helper: helpers,
    turn: turn,
    ui: ui,
    validate: validate,
    card: cards
  },
}

/* main.js */
import Functions from './functions.js';
Vue.prototype.$myFn = Functions;

Expected HMR to work but instead get a full page reload when making changes to functions.js (or any underlying js file imported in functions.js)


Solution

  • Adding your own objects and functions to the Vue prototype is a bit of an anti-pattern. In this case, Webpack can't determine the extent of the changes made so it falls back to a page reload. This is because ES modules can be statically analysed whereas global objects cannot be.

    Here's some articles about static analysis:

    Remove the functions from the Vue protoype and always use ES modules to structure your functions. Then you can import them into other modules or components without using the legacy style global hack approach of yesteryear.