zoukankan      html  css  js  c++  java
  • HMR

    HTR:hot module replacement 热模块替换 / 模块热替换

    作用:一个模块发生变化,只会重新打包这一个模块(而不是打包所有模块),极大的提升构建速度

       会在应用程序运行过程中替换、添加或删除模块,而无需重新加载整个页面,主要是通过以下方式:

        ①保留在完全重新加载页面时丢失的应用程序状态

        ②只更新变更内容

        ③调整样式更加快速,相当于在浏览器调试器中更改样式

    webpack 配置:

    const { resolve } = require('path');
    const HtmlWebpackPlugin = require('html-webpack-plugin');
    
    module.exports = {
      entry: ['./src/js/index.js','./src/index.html'],
      output: {
        filename: 'js/bundle.js',
        path: resolve(__dirname, 'build')
      },
      module: {
        rules: [
          // loader的配置
          {
            // 处理less资源
            test: /.less$/,
            use: ['style-loader', 'css-loader', 'less-loader']
          },
          {
            // 处理css资源
            test: /.css$/,
            use: ['style-loader', 'css-loader']
          },
          {
            // 处理图片资源
            test: /.(jpg|png|gif)$/,
            loader: 'url-loader',
            options: {
              limit: 8 * 1024,
              name: '[hash:10].[ext]',
              outputPath: 'imgs'
            }
          },
          {
            // 处理html中img资源
            test: /.html$/,
            loader: 'html-loader'
          },
          {
            // 处理其他资源
            exclude: /.(html|js|css|less|jpg|png|gif)/,
            loader: 'file-loader',
            options: {
              name: '[hash:10].[ext]',
              outputPath: 'media'
            }
          }
        ]
      },
      plugins: [
        // plugins的配置
        new HtmlWebpackPlugin({
          template: './src/index.html'
        })
      ],
      mode: 'development',
      devServer: {
        contentBase: resolve(__dirname, 'build'),
        compress: true,
        port: 3000,
        open: true,
        hot: true //开启HMR功能, 当修改了webpack配置,新配置要想生效,必须重新npx webpack服务
      }
    };

    css文件:可以使用 HMR 功能,因为 style-loader 内部实现了(所以开发环境需要用到 style-loader)

     

    js 文件:默认不能使用 HMR 功能,需要修改 js 代码时,就添加支持支持HTR功能的代码

        注意,HMR 功能只能 处理非入口 js 文件,不能处理入口 js 

    import '../css/iconfont.css';
    import '../css/index.less';
    import print from './b'
    
    console.log('index.js被加载')
    print()
    
    if (module.hot) { // 一旦 module.hot 为true,说明开启了HMR功能。 --> 让HMR功能代码生效
      module.hot.accept('./b.js', function () { //方法会监听 b.js 文件的变化,一旦发生变化,其他模块不会重新打包构建。
        print(); //会执行后面的回调函数
      });
    }
    

    html 文件:默认不能使用 HMR 功能,同时还会导致问题,html 文件不能热更新了,

          解决方法:修改 entry 入口,将 html 文件引入

     

  • 相关阅读:
    Azure HPC Pack Cluster添加辅助节点
    Azure HPC Pack 辅助节点模板配置
    Azure HPC Pack配置管理系列(PART6)
    Windows HPC Pack 2012 R2配置
    Azure HPC Pack 节点提升成域控制器
    Azure HPC Pack VM 节点创建和配置
    Azure HPC Pack 部署必要条件准备
    Azure HPC Pack 基础拓扑概述
    Azure VM 性能计数器配置
    Maven私仓配置
  • 原文地址:https://www.cnblogs.com/shanlu0000/p/13052359.html
Copyright © 2011-2022 走看看