5.webpack4抽离模块,懒加载,热更新简单使用

萌新自己学习webpack做的简单配置,如有错误请多包含,也可指点,谢谢.

# 抽离公共代码

# 懒加载
# es6 jsonp实现动态加载文件

# 热更新
# 使用devServer的hot属性开启热更新
# 使用webpack自带的NamedModulesPlugin插件打印被更新的模块路径
# 使用webpack自带的HotModuleReplacementPlugin插件开启热更新监控
# 在入口文件中判断一下是否开启了热更新,并且指定需要检查的文件.
# 如果开启了热更新,对应文件改动就不会刷新页面.
# index.js
# if (module.hot) {
#   module.hot.accept('./source.js',()=>{
#     console.log('文件更新了');
#     let str = require('./source')
#     console.log('新的',str);
#   })
# }

webpack.config.js

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const webpack = require('webpack')
module.exports = {
  mode: 'development',
  devServer: {
    hot: true,  // 启用热更新
  },
  optimization: {
    splitChunks: {  // 分割代码块,只有多入口才需要把公用的资源抽出来
      cacheGroups: {  // 缓存组
        common: { // 公共模块
          minSize: 0,
          minChunks: 2,
          chunks: 'initial',
        },
        vender: {
          priority: 1,  // 权重,设置先抽离这里的文件,然后再抽离其它的
          test: /node_modules/,  // 只会抽离指定文件夹中符合要求的模块
          minSize: 0,
          minChunks: 2,
          chunks: 'initial',
        }
      }
    }
  },
  // 多入口
  entry: {
    home: './src/index.js',
    other: './src/other.js'
  },
  output: {
    // [name] home,other 
    filename: '[name].js',
    path: path.resolve(__dirname,'dist')
  },
  plugins: [ // 数组 存放所有的webpack插件
    new HtmlWebpackPlugin({
      template: './index.html', // 模板
      filename: 'home.html', // 打包后文件名
      chunks: ['home'], // 配置引用资源
    }),
    new HtmlWebpackPlugin({
      template: './index.html', // 模板
      filename: 'other.html', // 打包后文件名
      chunks: ['other'], // 配置引用资源
    }),
    new webpack.NamedModulesPlugin(), // 打印更新的模块路径
    new webpack.HotModuleReplacementPlugin()  // 热更新插件
  ],
}

index.js

console.log('hello home')
import './a'
import './b'
console.log('index.js');

import $ from 'jquery'
console.log($);

// 懒加载
// let btn = document.createElement('button')
// btn.innerText="小夫,在吗"
// btn.addEventListener('click',()=>{
//   console.log('小夫,我要进来了哦');
//   // es6 jsonp实现动态加载文件
//   import('./source.js').then(data=>{
//     console.log(data.default);
//   })
// })
// document.body.appendChild(btn)

import str from './source'
console.log(str);
// css-loader style-loader vue-loader 已经实现了自动热更新的配置 无需像下面一样判断是否开启了热更新
if (module.hot) {
  module.hot.accept('./source.js',()=>{
    console.log('文件更新了');
    let str = require('./source')
    console.log('新的',str);
  })
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值