问题
So with webpack, HMR will only work if you have this code in your module or a parent of your module:
if (module.hot) {
module.hot.accept()
}
Which makes me wonder why you would ever decline HMR in the first place. Is there a performance cost or other negative side effect to using it?
The docs aren't very clear on the issue.
回答1:
You can only use HMR if your code
- is either stateless (like CSS) or
- provides preparations to clean up the old state
Since most code is not stateless, there is some extra work necessary. A common way to achieve this is by replacing the exported functions with proxies (the react-hot-loader works in a similar fashion). Thus it is possible to replace the actual implementations behind the proxies without updating other dependencies.
For example, imagine this (buggy) module:
function add(a, b) {
return a - b;
}
export add;
After noticing the bug, you cannot just swap out the add
function on the fly because other modules hold references to it. That's why you need a proxy that wraps the exported functions:
function _add(a, b) {
return a - b;
}
export function add(a, b) {
return _add(a, b);
};
Now you can easily swap out _add
without updating other modules. This works pretty well with functions but fails with other types like exported objects, numbers, strings. With ES2015 proxies, however, it will be possible to export placeholders that work like a proxy on all kind of types.
So, the challenge with HMR is that you need to replace the old code with the new code without leaving any weird state. And that's still difficult to do in a generic way.
来源:https://stackoverflow.com/questions/35255941/when-shouldnt-you-accept-webpack-hot-module-reloading