webpack学习(七):启用 HMR(模块热替换)

demo地址: https://github.com/Lkkkkkkg/webpack-demo
上次使用 webpack-dev-serve : https://blog.csdn.net/qq593249106/article/details/84922572

当前目录结构 :

|- /dist //用于放打包后文件的文件夹
  |- app.bundle.js //出口文件
  |- print.bundle.js //出口文件
  |- index.html //模板文件
|- /node_modules
|- /src //用于放源文件的文件夹
  |- index.js //入口文件
  |- print.js 
|- package.json
|- webpack.config.js //webpack配置文件

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');


module.exports = {
   
    entry: {
   
        app: './src/index.js'
        // print: './src/print.js'
    },
    devtool: 'inline-source-map', // 不同选项适用于不同环境
    devServer: {
   
        contentBase: './dist', //将dist目录下的文件(index.html)作为可访问文件, 如果不写这个参数则默认与webpack.cofig.js的同级目录
        port: 8080 //端口号设为8080, 默认也是8080
    },
    plugins: [ //webpack 通过 plugins 实现各种功能, 比如 html-webpack-plugin 使用模版生成 html 文件
        new CleanWebpackPlugin(['dist']), //设置清除的目录
        new HtmlWebpackPlugin({
   
            filename: 'index.html', //设置生成的HTML文件的名称, 支持指定子目录,如:assets/admin.html
        })
    ],
    output: {
   
        filename: '[name].bundle.js', //根据入口文件输出不同出口文件
        path: path.resolve(__dirname, 'dist')
    }
};

这里把配置的 入口文件 print.js 给去掉了, 因为 print.js 被 入口文件 index.js 应用了

HMR(模块热替换)

模块热替换(Hot Module Replacement 或 HMR)是 webpack 提供的最有用的功能之一, 它允许在运行时更新各种模块, 而无需进行完全刷新
比如在这个现在修改 print.js 里面的内容, 使用 HMR 就可以只更新 print.js 里面的内容而不用重新加在整个页面

启用HMR

启用这个功能很简答, 只需要修改一下 webpack.config.js 的配置, 使用 webpack 内置的 HMR 插件就可以了
webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const webpack = require
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值