webpack4.x实现热更新

前言

webpackwebapck-dev-server 包会启动一个开发服务器,当修改入口文件或者入口文件中引入的其他文件时,webpack 会自动编译入口文件,然后刷新整个页面。然我们仅仅修改了一个文件就刷新了整个页面,这样的操作太不划算了,此时可以用到 webpack-dev-server 的热更新功能。

环境

初始化

yarn init -D

安装必要的包

yarn add webpack webpack-cli webpack-dev-server html-webpack-plugin -D

目录

在这里插入图片描述

未启动热更新

效果

当没有启用热更新时效果如下:
在这里插入图片描述
可以观察到,一旦修改了文件,则浏览器会自动刷新页面。

代码

public/index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>webpack4.x</title>
</head>
<body>

</body>
</html>

src/index.js

import str from './source'

console.log(str)

src/source.js

export default 'hello world'

webpack.config.js

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const webpack = require('webpack')
module.exports = {
  mode: 'production',
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  devServer: {
    port: 9000,
    // 自动打开浏览器
    open: true,
    // 告诉服务器从哪里dist目录中提供内容
    contentBase: './dist'
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './public/index.html'
    })
  ]
}

启用热更新

效果

当启用热更新时效果如下:
在这里插入图片描述
可以观察到,浏览器并未刷新,仅仅更新了修改了的文件。

代码

webpack.config.js

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const webpack = require('webpack')
module.exports = {
  mode: 'production',
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  devServer: {
    // 只更新修改的部分,而不是刷新整个页面
    hot: true,
    port: 9000,
    // 自动打开浏览器
    open: true,
    // 告诉服务器从哪里dist目录中提供内容
    contentBase: './dist'
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './public/index.html'
    }),
    // 打印更新的模块路径
    new webpack.NamedModulesPlugin(),
    // 热更新插件
    new webpack.HotModuleReplacementPlugin()
  ]
}

当启用热更新后,需要在 index.js 入口文件中添加热更新加载文件。
src/index.js

import str from './source'

console.log(str)

if (module.hot) {
  module.hot.accept('./source', () => {
    const str = require('./source').default
    console.log(str)
  })
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值