zoukankan      html  css  js  c++  java
  • Hot Module Replacement [热模块替换]

    安装了webpack-dev-server后 , 配置 "start": "webpack-dev-server" 然后运行 npm start 会开起一个web服务。

    这时当我们的代码发生变化时,浏览器会自动刷新,显示变更后的代码所展示的内容。但是,这种情况下会将没有发生改变的部分也刷新,也就是全局刷新。如果想做到局部刷新,就需要 Hot Module Replacement [热模块替换]的支持。

    const webpack = require('webpack')
    
    module.exports = {
        plugins: [
          new webpack.HotModuleReplacementPlugin()
        ],
        devServer: {
          contentBase: './dist',   // 在哪个目录下开启web服务
          port: 3000,                
          open: true,                 // 自动打开浏览器
          hot: true,                   // 开启热模块替换功能
          hotOnly: true             // 如果开启的热模块替换功能失效,不额外做其他事情,只是刷新一下页面
      },
    }

     当你写完这些配置后去更改css样式时,会发现热模块替换已经有效果了。但是,当我们修改,js文件时会发现修改的内容没有在页面上显示。这是因为,css-loader 帮我们做了一些事情。

    if (module.hot) {
        module.hot.accept('xxx.css', () => {
             // ...
        })
    }

    如果项让js文件也实现热模块替换,也需要编写相应的逻辑。

    index.js

    import Counter from './counter'
    import Numb from './number'
    
    Counter()
    Numb()
    
    if (module.hot) {
      module.hot.accept('./number', () => {
        var nu = document.getElementById('nu')
        document.body.removeChild(nu)
        Numb()
      })
    }

    counter.js

    function counter() {
      var div = document.createElement('div')
      div.setAttribute('id', 'co')
      div.innerHTML = 1
      div.onclick = function() {
        div.innerHTML =  parseInt(div.innerHTML, 10) + 1
      }
      document.body.appendChild(div)
    }
    
    export default counter

    number.js

    function number() {
      var div = document.createElement('div')
      div.setAttribute('id', 'nu')
      div.innerHTML = 2000
      document.body.appendChild(div)
    }
    
    export default number
  • 相关阅读:
    21.Merge Two Sorted Lists 、23. Merge k Sorted Lists
    34. Find First and Last Position of Element in Sorted Array
    leetcode 20. Valid Parentheses 、32. Longest Valid Parentheses 、301. Remove Invalid Parentheses
    31. Next Permutation
    17. Letter Combinations of a Phone Number
    android 常见分辨率(mdpi、hdpi 、xhdpi、xxhdpi )及屏幕适配注意事项
    oc 异常处理
    oc 类型判断
    oc Delegate
    oc 协议
  • 原文地址:https://www.cnblogs.com/ladybug7/p/12325340.html
Copyright © 2011-2022 走看看