webpack优化环境配置 - 24.lazy loading

//懒加载: 当文件需要时才加载~
//预加载: prefetch: 会在使用之前,提前加载js文件 (webpackPrefetch: true)

//正常加载可以认为是并行加载(同一时间加载多个文件)。
// 预加载: prefetch: 等其他资源加载完毕,浏览器空闲了,再偷偷加载资源。(但是兼容性差,只能在PC端一些高版本浏览器使用,在移动端,或者IE浏览器中有相当大的兼容问题)

 

1.文件结构

 

 2.代码

index.js

console.log('index.js文件被加载了~')

import {mul} from './test'

document.getElementById("btn").onclick = function () {
    //懒加载: 当文件需要时才加载~
    //预加载: prefetch: 会在使用之前,提前加载js文件 (webpackPrefetch: true)

    //正常加载可以认为是并行加载(同一时间加载多个文件)。
    // 预加载: prefetch: 等其他资源加载完毕,浏览器空闲了,再偷偷加载资源。(但是兼容性差,只能在PC端一些高版本浏览器使用,在移动端,或者IE浏览器中有相当大的兼容问题)
    import(/*webpackChunkName: 'test', webpackPrefetch: true */'./test')
        .then(({mul}) => {
            console.log(mul(4, 5));
        })
        .catch((err) => {
            console.log('err...:', err)
        })
}

test.js

console.log('test.js文件被加载了~')
export function mul(x, y) {
    return x * y;
}

export function count(x, y) {
    return x - y;
}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>webpack</title>
</head>
<body>
    <h5>hello lazy loading</h5>
    <button id="btn">BTN</button>
</body>
</html>

webpack.config.js

const {resolve} = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    entry: './src/js/index.js',
    output: {
        filename: "js/[name].[contenthash:10].js",
        path: resolve(__dirname, "build")
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: "./src/index.html",
            minify: {
                collapseWhitespace: true,
                removeComments: true
            }
        })
    ],
    optimization:{
      splitChunks: {
          chunks: "all"
      }
    },
    mode: 'production'
}

3.打包

$ webpack

 

 end~

 

posted @ 2022-09-08 18:22  Evengod  阅读(35)  评论(0编辑  收藏  举报