7

I have a Vue.js site with Webpack Dev Middleware (served via an ASP.NET Core site by HTTP.sys web server, though I'm guessing that doesn't matter). Does anyone know how I can set up my site to clear the browser's Javascript console on every hot reload event?

Here's the only related link I can find, but it seems to be for a web server I am not using. I'm not sure why the particular web server would matter.

Patrick Szalapski
  • 8,738
  • 11
  • 67
  • 129

2 Answers2

13

In my main app .js file:

if (module.hot) {
    module.hot.accept() // already had this init code 

    module.hot.addStatusHandler(status => {
        if (status === 'prepare') console.clear()
    })
}

That got it to work consistently for me.

See also https://webpack.js.org/api/hot-module-replacement/#addstatushandler .

Patrick Szalapski
  • 8,738
  • 11
  • 67
  • 129
11

your link contains the response for your question. Just add in your main.js file:

window.addEventListener('message', (e) => {
  if (e.data && typeof e.data === 'string' && e.data.match(/webpackHotUpdate/)) {
    console.log('hot reload happened')
    console.clear()
  }
})

Example of a complete main.js file:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

Vue.config.productionTip = false

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

window.addEventListener('message', (e) => {
  if (e.data && typeof e.data === 'string' && e.data.match(/webpackHotUpdate/)) {
    console.log('hot reload happened')
    console.clear()
  }
})

EDIT: I didn't read your answers to the github issue. Could you provide some kind of JSON.stringify(e) on your event message on multiple events so we can check what you have?

Hammerbot
  • 15,696
  • 9
  • 61
  • 103
  • What happens when you `console.log(e instanceof MessageEvent)`? Indeed when I `JSON.stringify(e)` I have only `{"isTrusted":true}` but when I `JSON.stringify(e.data)` I have all sorts of data – Hammerbot Dec 26 '18 at 14:29
  • Hmm, looks like I had the code in the wrong place before? Not sure. Anyway, trying again, I get the following JSON in `e.data.payload.payload` on a HMR event: https://jsfiddle.net/szal/qp8rojng/ - no "webpackHotUpdate" in there, and I see nothing to distinguish a HMR event from other events where`e.data.payload.event === 'flush'`. – Patrick Szalapski Dec 26 '18 at 14:43
  • Good idea, we seem closer. Any further ideas? – Patrick Szalapski Dec 26 '18 at 14:48
  • All right, so this is just one message that you receive, are you sure you don't receive other messages? I just want to make it sure. In my case, `e.data` is just a string when Hot Reload happens but I also have the kind of message you pasted in the fiddle sometimes – Hammerbot Dec 26 '18 at 14:52
  • Yes, I don't receive other events here. I think I figured it out; see my answer. Thanks for prompting additional thoughts. – Patrick Szalapski Dec 26 '18 at 15:07