• 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~

  • 相关阅读:
    Java 1.7.0_21b11 Code Execution
    nginx NULLByte 任意代码执行漏洞
    nginx ‘ngx_http_close_connection()’远程整数溢出漏洞
    WordPress WP Super Cache插件任意代码执行漏洞
    memcached 远程拒绝服务漏洞
    原环套原环
    要去哈尔滨了
    母亲节就要到了,你忘了吗?
    对于流媒体服务的一点概念
    有了螃蟹让心情好一点
  • 原文地址:https://www.cnblogs.com/sener/p/16670482.html
Copyright © 2020-2023  润新知