您何时不应该接受webpack Hot Module Reloading? [英] When shouldn't you accept webpack Hot Module Reloading?

查看:190
本文介绍了您何时不应该接受webpack Hot Module Reloading?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,对于webpack,仅当您在模块中或模块的父级中包含以下代码时,HMR才起作用:

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()
}

这让我想知道为什么您会一开始拒绝HMR.使用它会产生性能成本或其他负面影响吗?

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?

文档不太清楚问题.

推荐答案

如果您的代码只能使用HMR

You can only use HMR if your code

  • 是无状态的(例如CSS)或
  • 为清理旧状态提供了准备

由于大多数代码不是无状态的,因此需要做一些额外的工作.实现此目的的一种常见方法是用代理替换导出的函数( react-hot-loader 以类似的方式工作).因此,有可能在不更新其他依赖项的情况下替换代理后面的实际实现.

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;

在注意到该错误之后,您不能随便换掉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);
};

现在,您可以轻松换出_add,而无需更新其他模块.这对函数很好用,但对其他类型(如导出的对象,数字,字符串)则无效.但是,使用 ES2015代理,它将是可以导出在所有类型上都可以像代理一样工作的占位符.

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.

因此,HMR的挑战在于您需要用新代码替换旧代码,而又不离开任何怪异状态.而且,以一般方式仍然很难做到这一点.

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.

这篇关于您何时不应该接受webpack Hot Module Reloading?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆