本文适用于模块热更换的哪个方面? [英] What aspect of Hot Module Replacement is this article for?

查看:17
本文介绍了本文适用于模块热更换的哪个方面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Webpack 并且遇到了这篇文章.我大致了解什么是热模块更换(HMR).我可以通过以下示例代码配置 webpack HMR 插件:

I am learning Webpack and come across this article. I have general idea of what is hot module replacement(HMR). I can configure webpack HMR plugin by following example code:

var plugins = [ new webpack.HotModuleReplacementPlugin(), // using HMR plugin
            new HtmlWebpackPlugin({template: './index.html'})
        ]; 

module.exports = {
    // webpack config object
    context: entryBasePath,
    entry:{
        app: ['webpack/hot/dev-server', './bootstrap.js']
    },
    output: {
        path: outputBasePath,
        filename: './bundle.js',
        sourceMapFilename: '[file].map' // set source map output name rule
    },
    devtool: 'source-map', // enable source map
    plugins: plugins, 
    module: {
        loaders: [
            { test: /\.scss$/, loader: 'style!css!sass'}, 
            { test: /\.tpl$/,  loader: 'raw' }, 
            {
        test: /\.woff2?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'url?limit=10000'
      },
      {
        test: /\.(ttf|eot|svg)(\?[\s\S]+)?$/,
        loader: 'file'
      },
      { test: /bootstrap-sass\/assets\/javascripts\//, loader: 'imports?jQuery=jquery' }

        ]
    }

}

我的问题是这篇文章的哪些方面试图解释关于 Webpack 热模块更换?我在哪里可以使用该页面上提供的示例代码?

My question is What aspect of this article is trying to explain about Webpack Hot Module Replacement? Where can I use the example code provided on that page?

简而言之,我的问题是这个 关于?

In short, my question is what(the hell) is this about?

推荐答案

热模块替换 (HMR) 是在应用程序运行时交换代码的功能.它允许您在保留应用程序状态的同时编辑代码.这对于样式特别有用,您通常只想在不重新加载浏览器的情况下更新样式.

Hot Module Replacement (HMR) is a feature to swap out code while the application is running. It allows you to edit code while preserving the state of the application. This is especially useful for styling, where you usually just want to update styles without reloading the browser.

然而,这只有在代码提供特殊钩子来删除以前的代码、撤消所有副作用并注入新代码时才有可能.典型的副作用:注册事件监听器、在对象中存储数据、修改全局状态.

This, however, is only possible if the code provides special hooks to remove the previous code, undo all side-effects and inject the new code. Typical side-effects: are registering event listeners, storing data in objects, modifying global state.

例如,在应用程序运行时替换 CSS 是一项简单的任务,因为 CSS 根据定义没有副作用.为了理解 HMR 的内部结构,让我们来看看 style-loader:

Replacing CSS while the application is running, for instance, is an easy task since CSS is side-effect free per definition. In order to understand the internals of HMR, let's take a look at the style-loader:

样式加载器附加这个特殊代码 来处理 HMR(我已经删除了一些对本示例不重要的代码):

The style-loader appends this special code to handle HMR (I've removed some code that is not important for this example):

if (module.hot) {
    // When the styles change, update the <style> tags
    module.hot.accept(loaderUtils.stringifyRequest(this, !!remainingRequest), function () {
        var newContent = require(loaderUtils.stringifyRequest(this, !!remainingRequest));
        update(newContent);
    });
    // When the module is disposed, remove the <style> tags
    module.hot.dispose(function () {
        update();
    });
}

  • if (module.hot) { 检查是否启用了 HMR
  • module.hot.accept(, handler) 注册一个处理程序来注入新代码
  • module.hot.dispose(handler) 注册一个处理程序来处理旧代码
    • if (module.hot) { checks, if HMR is enabled
    • module.hot.accept(<module identifier>, handler) registers a handler to inject new code
    • module.hot.dispose(handler) registers a handler to dispose old code
    • 更新函数难以阅读,但它基本上只是向 document.head 添加新样式表并删除未使用的样式表.

      The update function is hard to read, but it basically just adds new stylesheets to document.head and removes unused stylesheets.

      React 中的 HMR 有点复杂,并且在过去的几个月中经历了一些严重的重构.但基本原则是每个导出的组件都包装在一个代理中.代理是一个对象,其行为类似于另一个对象.这可以通过将所有函数转发到真实"对象或使用 ES2015 代理(显然更强大).通过这种方式,可以轻松地换出原始对象,而无需更新任何其他组件.我在另一个 SO 答案中对此进行了更详细的描述.

      HMR in React is a bit more complex and has gone through some serious refactoring in the last couple of month. But the basic principle is that every exported component is wrapped inside a proxy. A proxy is an object that acts like another object. This can either be achieved by forwarding all functions to the "real" object or by using ES2015 proxies (which are obviously much more powerful). This way, the original object can easily be swapped out without updating any other components. I've described this a bit more in detail in another SO answer.

      为了使 HMR 工作,需要满足一些要求:

      In order to make HMR work, there are some requirements to be met:

      • 您的代码需要 module.hot.acceptmodule.hot.dispose 的钩子来处理代码更新.这通常是通过加载器(例如,样式加载器)或 babel 转换(例如,babel-preset-react-hmre 预设).从技术上讲,您也可以在每个模块中为自己编写这些钩子……也许这是开始学习内部结构的好方法.如果更新的模块不包含此代码或无法处理更新,则更新将被拒绝并且 webpack 将重新加载浏览器窗口.这可能看起来像 HMR,但实际上只是浏览器刷新.

      • Your code requires hooks for module.hot.accept and module.hot.dispose to handle code updates. This is usually achieved through a loader (for instance, the style-loader) or a babel transformation (for instance, the babel-preset-react-hmre preset). Technically, you could also write these hooks in every module for yourself... maybe that's a good way to start learning the internals. If an updated module does not contain this code or is unable to handle the update, the update will be rejected and webpack will reload the browser window. This might look like HMR but is actually just a browser refresh.

      您需要客户端和服务器上的一些基础设施来建立 WebSockets 连接、将新代码推送到客户端并通知所有过时的模块来处理更新.最简单的方法是使用带有 webpack-dev-server --hot --inline 的 webpack-dev-server.不需要其他代码.特别是不要在 webpack.config.js 中添加 HMR 插件或任何 webpack-dev-server 的东西——它们都将通过 --hot --inline 启用.有更多的方法来配置它——这实际上可能是需要的,具体取决于您的设置.这就是为什么这部分对于新手来说常常如此混乱的原因.

      You need some infrastructure on the client and the server to establish a WebSockets connection, to push new code to the client and to inform all outdated modules to handle the update. The most easy way to achieve this is by using the webpack-dev-server with webpack-dev-server --hot --inline. There is no other code required. Especially don't add the HMR plugin or any webpack-dev-server stuff to the webpack.config.js – it will all be enabled with --hot --inline. There are more ways to configure this – which might actually be required depending on your setup. That's usually why this part is often so confusing for newcomers.

      Webpack 需要在监视模式下运行,因为我们只想处理更改的文件.当您使用 webpack-dev-serverwebpack-dev-middleware 时,您不需要在配置中添加任何内容,它已经将 webpack 编译器进入监视模式lazy: false,当然).

      Webpack needs to run in watch mode since we only want to handle changed files. You don't need to add anything to the config when you're using the webpack-dev-server or the webpack-dev-middleware, it already puts the webpack compiler into watch-mode (only in case of lazy: false, of course).

      这篇关于本文适用于模块热更换的哪个方面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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