18.webpack优化配置-懒加载和预加载

(一) 懒加载

  1. webpack的配置文件就是基本的配置,

    const path = require('path');
    
    const HtmlWebpackPlugin = require("html-webpack-plugin")
    
    module.exports = {
          
          
        mode: 'production',
        entry: './src/js/index.js',
        output: {
          
          
            filename: 'js/[name][contenthash:8].js',
            path: path.resolve(__dirname, 'bulid'),
        },
        plugins: [
            new HtmlWebpackPlugin({
          
          
                template: './src/index.html'
            })
        ]
    }
    
  2. 模板文件index.html

    <button id="btn">按钮</button>
    
  3. 在入口文件index.js中

    console.log('index.js被加载');
    
    //当按钮点击后base.js文件被加载然后调用base.js文件中的mul函数
    document.getElementById('btn').onclick = function () {
          
          
        import( /* webpackChunkName: 'base'*/ './base').then(({
          
          mul}) => {
          
          
            console.log(mul(40, 3));
        }).catch((err) => {
          
          
            console.log(`base.js加载失败:${
            
            err}`);
        });
    }
    
  4. base.js文件内容

    console.log('base.js被加载');
    
    export function mul(a, b) {
          
          
      return a - b;
    }
    
  5. 打包

    webpack
    

(二) 预加载

  • 预加载prefetch:会在使用之前,提前加载js
  • 文件正常加载可以认为是并行加载(同一时间加载多个文件),预加载是等其他资源加载完毕,浏览器空闲了,再偷偷加载资源。
  • 兼容性比较差,慎用。
  1. 在懒加载的基础上,添加webpackPrefetch:true设置为预加载,修改入口文件index.js

    console.log('index.js被加载');
    
    document.getElementById('btn').onclick = function () {
          
          
        import( /* webpackChunkName: 'base',webpackPrefetch:true*/ './base').then(({
          
          
            mul
        }) => {
          
          
            console.log(mul(40, 3));
        }).catch((err) => {
          
          
            console.log(`base.js加载失败:${
            
            err}`);
        });
    }
    
  2. 这是可以在html文件中看到如下图所示的代码
    在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/kouzuhuai2956/article/details/108083798