首页 > 其他 > 详细

HMR

时间:2020-06-05 22:57:12      阅读:62      评论:0      收藏:0      [点我收藏+]

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 文件引入

 技术分享图片

 

HMR

原文:https://www.cnblogs.com/shanlu0000/p/13052359.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!