Why there is "if (module.hot){ ... }" ?
justb opened this issue · comments
When I delete "document.body.appendChild(sideEffectNode);", and re-add this line, the hmr does not work. What should I do to make hmr work under any condition?
Hey @justb - good question. This fails because my module.hot.dispose
function fails with this error:
Cannot read property 'removeChild' of null
That failure is on this line:
sideEffectNode.parentNode.removeChild(sideEffectNode);
And that error happens because sideEffectNode
does not have a parentNode if you don't add it to the document.
The quick fix for this is to change the dispose function to look like this:
sideEffectNode && sideEffectNode.parentNode && sideEffectNode.parentNode.removeChild(sideEffectNode);
If you check to make sure that the node has a parent before calling removeChild()
on it, then the HMR dispose function will not throw an error, and everything is fine.
The lesson here is that the HMR code shouldn't make any assumptions about that the code that is being hot-reloaded. This repository does make assumptions because it is a small contrived example.
Hope this helps!