1

I am trying to create a minimal working example of hot module replacement using webpack-dev-server. Basically, I want to use webpack to prepare a bundle.js file containing a few modules modules that will be loaded and run in an HTML page invoked by a browser.

An example of module moduleA that I would like to make hot-swappable is the following:

'use strict'
var myA = function(){ return 'a'; }
module.exports = myA;
if (module.hot) { module.hot.accept(); }

And then there is a main module (which I don't plan to hot-swap) that uses it:

'use strict'
var myA = require('./moduleA');
var myB = require('./moduleB');
function clickMe() { alert(myA() + myB() + "-test"); }
document.getElementById('theButton').onclick = clickMe;
if (module.hot) {
  module.hot.accept('./moduleA', function() { myA = require('./moduleA');});
  module.hot.accept('./moduleB', function() { myB = require('./moduleB');});
}

If I modify e.g. the value returned by myA I'd expect the button alert text to change; indeed, the console displays all the messages between the HRM server and the runtime, but the click on the button shows still the older alert value.

I have verified that the hot-swap handlers in the main module do not run when moduleA gets swapped. I understood that some kind of hot-swapping event bubbles up the chain of require's, but apparently that's not happening in my case.

Unfortunately most examples around are either too complex, not JS-based or for some reason behaving differently from what I'd expect.

My basic question is: can anyone show me how I should modify my simple modules to make them truly hot-swappable?.

For whoever wants the whole picture, here is the code

4

0 回答 0