• webpack优化环境配置 23.code split(3)


    1.文件结构

      

    2.代码

    index.js

    function sum(...arg) {
        return arg.reduce((p, c) => p + c, 0);
    }
    
    /*
    * 通过js代码,让某个文件被单独打包成一个chunk
    * import 动态导入语法: 能将某个文件单独打包
    * */
    
    //webpackChunkName: 指定打包后生成文件的文件名
    import (/*webpackChunkName: 'test'*/'./test')
        .then(({mul, count}) => {
            //文件打包成功~
            // eslint-disable-next-line
            console.log("mul:", mul(2, 3))
        })
        .catch(() => {
            // eslint-disable-next-line
            console.log('文件打包失败!!!')
        })
    
    // eslint-disable-next-line
    console.log(sum(1, 2, 3, 4, 5, 6));

    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 catch</h5>
    </body>
    </html>

    webpack.config.js

    const {resolve} = require('path')
    const HtmlWebpackPlugin = require('html-webpack-plugin')
    
    module.exports = {
        //单入口
        entry: './src/js/index.js',
        //多入口
        // entry:{
        //     index:'./src/js/index.js',
        //     test:'./src/js/test.js'
        // },
        output: {
            // [name] 文件名
            filename: "js/[name].[contenthash:10].js",
            path: resolve(__dirname, "build")
        },
        plugins: [
            new HtmlWebpackPlugin({
                template: "./src/index.html",
                minify: {
                    collapseWhitespace: true,
                    removeComments: true
                }
            })
        ],
        /*
        * 1. 可以将 node_modules 中的代码,单独打包一个 chunk 最终输出
        * 2. 自动分析多入口chunk中,有没有公共的文件。如果有会打包成单独一个chunk
        * */
        optimization:{
          splitChunks: {
              chunks: "all"
          }
        },
        mode: 'production',
    }

    3.打包

    $ webpack

     end~

  • 相关阅读:
    Autofac 学习简易教程随笔(一)
    实现Entity Framework SQLite Code First 开发
    Entity Framework SQLite 开发及实现简单的自定义Migration Engine
    MSSQLServer和SQL Server Express、LocalDB的区别
    .gitignore文件
    Entity Framework MSSQL Code First 开发
    页面为要加<!DOCTYPE html>
    数字图像处理(下)
    数字图像处理(上)
    列表
  • 原文地址:https://www.cnblogs.com/sener/p/16670473.html
Copyright © 2020-2023  润新知