当前位置: 首页 > article >正文

webpack 优化

打包优化

    • webpack 优化
      • 1、依赖转化,兼容低版本浏览器
      • 2、生产环境关闭sourceMap
      • 3、打包输出目录名称修改和静态资源的存放
      • 4、修改图标
      • 5、修改webpack配置
        • 5-1、写在此处的配置可以覆盖掉脚手架本来就预设上有的配置
        • 5-2、写在此处的都是预设没有配置的,脚手架本来就有的配置是不会覆盖的
      • 6、完整配置
    • vite 优化

webpack 优化

1、依赖转化,兼容低版本浏览器

// 对依赖进行转换
transpileDependencies: true,

2、生产环境关闭sourceMap

// 生产关闭sourceMap
productionSourceMap: false,

3、打包输出目录名称修改和静态资源的存放

outputDir: 'bundle', // 打包后文件的目录 (默认为dist)
assetsDir: 'static', //  outputDir的静态资源(js、css、img、fonts)目录  默认为‘’没有单独目录js/css/img在根目录中。

4、修改图标

// 修改浏览器的icon图标,不加下面的,修改浏览器图标不生效
pwa: {
    iconPaths: {
        favicon32: 'favicon.ico',
        favicon16: 'favicon.ico',
        appleTouchIcon: 'favicon.ico',
        maskIcon: 'favicon.ico',
        msTileImage: 'favicon.ico',
    }
}

5、修改webpack配置

5-1、写在此处的配置可以覆盖掉脚手架本来就预设上有的配置
chainWebpack: config => {
    config.optimization.minimizer('terser').tap(args => {

        // 删除代码中的注释和打印,减少一点代码体积
        args.forEach(item => {
            if (item.hasOwnProperty('terserOptions')) {
                Object.assign(item['terserOptions'].compress, {
                    drop_debugger: true,
                    drop_console: true,
                    pure_funcs: ['console.log']
                })
            }
            item['terserOptions']['format'] = {
                comments: false
            }
        })
        return args
    })


    // 开启 gzip 压缩
    if (process.env.NODE_ENV === "production") {
        config.plugin('CompressionPlugin').use(
            new CompressionWebpackPlugin({
                test: /\.(js|css|less|scss|html)$/,   // 将 css、scss、less、html 进行压缩
                threshold: 10240, // 超过10kb的文件就压缩
                deleteOriginalAssets: false, // 不删除源文件
                minRatio: 0.8,   // 最小压缩率 0.8
                algorithm: 'gzip'
            })
        )
    }
}

5-2、写在此处的都是预设没有配置的,脚手架本来就有的配置是不会覆盖的
configureWebpack: {
   // 代码分割
   optimization: {
       splitChunks: {
           chunks: "all",

           // 定义一个cache组,将第三方的包抽离出来
           cacheGroups: {
               elementUI: {
                   // 抽离出来的名字
                   name: "element-chunk-vendors",
                   // 在node_modules包里面找
                   test: /[\\/]node_modules[\\/]_?element-ui(.*)/,
                   // 权重,越大优先打包
                   priority: 30,
               },
               vue: {
                   name: "vue-chunk-vendors",
                   test: /[\\/]node_modules[\\/]vue(.*)[\\/]/,
                   chunks: "initial",
                   priority: 20,
                   reuseExistingChunk: true,
               },
               vueRouter: {
                   name: "vueRouter-chunk-vendors",
                   test: /[\\/]node_modules[\\/]vue-router(.*)[\\/]/,
                   chunks: "initial",
                   priority: 19,
               },
               vuex: {
                   name: "vuex-chunk-vendors",
                   test: /[\\/]node_modules[\\/]vuex(.*)[\\/]/,
                   chunks: "initial",
                   priority: 18,
               },
               echarts: {
                   name: "echarts-chunk-vendors",
                   test: /[\\/]node_modules[\\/]echarts(.*)[\\/]/,
                   chunks: "initial",
                   priority: 17,
               },
               // 剩下的别忘记单独抽离
               libs: {
                   name: "chunk-libs-vendors",
                   test: /[\\/]node_modules[\\/]/,
                   priority: 1, // 权重最低,优先考虑前面内容
                   chunks: "initial",
               },

               // 针对自己写的代码,重复使用的满足下面的配置就会抽离出来单独打包,比如 utils 下面的包
               default: {
                   // 其他没有写的配置会使用上面的默认值
                   test: /[\\/]src(.*)[\\/]/,
                   name: "common-chunk",
                   minSize: 20000, // 超过 20kb,就会拆包
                   minChunks: 2,  // 引用两次就会拆包
                   priority: -10,
                   reuseExistingChunk: true
               }
           }
       }
   },

   // 配置别名
   resolve: {
       alias: {
           "#": path.resolve(__dirname, "src")
       }
   },

	// 分析插件
   plugins: [
       new BundleAnalyzer({
           analyzerMode: 'server',
           analyzerHost: '127.0.0.1',
           analyzerPort: 8088,
           reportFilename: 'report.html',
           defaultSizes: 'parsed',
           openAnalyzer: true,
           generateStatsFile: false,
           statsFilename: 'state.json',
           statsOptions: null,
           logLevel: 'info'
       })
   ]
}

6、完整配置

const path = require("path")
const { defineConfig } = require('@vue/cli-service')
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const BundleAnalyzer = require('webpack-bundle-analyzer').BundleAnalyzerPlugin

module.exports = defineConfig({
    // 对依赖进行转换
    transpileDependencies: true,

    // 生产关闭sourceMap
    productionSourceMap: false,

    outputDir: 'bundle', // 打包后文件的目录 (默认为dist)
    assetsDir: 'static', //  outputDir的静态资源(js、css、img、fonts)目录  默认为‘’没有单独目录js/css/img在根目录中。

    // 修改浏览器的icon图标
    pwa: {
        iconPaths: {
            favicon32: 'favicon.ico',
            favicon16: 'favicon.ico',
            appleTouchIcon: 'favicon.ico',
            maskIcon: 'favicon.ico',
            msTileImage: 'favicon.ico',
        }
    },


    // webpack 配置(写在此处的配置可以覆盖掉脚手架本来就预设上有的配置)
    chainWebpack: config => {
        config.optimization.minimizer('terser').tap(args => {

            // 删除代码中的注释和打印,减少一点代码体积
            args.forEach(item => {
                if (item.hasOwnProperty('terserOptions')) {
                    Object.assign(item['terserOptions'].compress, {
                        drop_debugger: true,
                        drop_console: true,
                        pure_funcs: ['console.log']
                    })
                }
                item['terserOptions']['format'] = {
                    comments: false
                }
            })
            return args
        })


        // 开启 gzip 压缩,对应的 nginx 也需要配置
        if (process.env.NODE_ENV === "production") {
            config.plugin('CompressionPlugin').use(
                new CompressionWebpackPlugin({
                    test: /\.(js|css|less|scss|html)$/,   // 将 css、scss、less、html 进行压缩
                    threshold: 10240, // 超过10kb的文件就压缩
                    deleteOriginalAssets: false, // 不删除源文件
                    minRatio: 0.8,   // 最小压缩率 0.8
                    algorithm: 'gzip'
                })
            )
        }
    },

    // webpack 配置(写在此处的都是预设没有配置的,脚手架本来就有的配置是不会覆盖的)
    configureWebpack: {
        // 代码分割
        optimization: {
            splitChunks: {
                chunks: "all",

                // 定义一个cache组,将第三方的包抽离出来
                cacheGroups: {
                    elementUI: {
                        // 抽离出来的名字
                        name: "element-chunk-vendors",
                        // 在node_modules包里面找
                        test: /[\\/]node_modules[\\/]_?element-ui(.*)/,
                        // 权重,越大优先打包
                        priority: 30,
                    },
                    vue: {
                        name: "vue-chunk-vendors",
                        test: /[\\/]node_modules[\\/]vue(.*)[\\/]/,
                        chunks: "initial",
                        priority: 20,
                        reuseExistingChunk: true,
                    },
                    vueRouter: {
                        name: "vueRouter-chunk-vendors",
                        test: /[\\/]node_modules[\\/]vue-router(.*)[\\/]/,
                        chunks: "initial",
                        priority: 19,
                    },
                    vuex: {
                        name: "vuex-chunk-vendors",
                        test: /[\\/]node_modules[\\/]vuex(.*)[\\/]/,
                        chunks: "initial",
                        priority: 18,
                    },
                    echarts: {
                        name: "echarts-chunk-vendors",
                        test: /[\\/]node_modules[\\/]echarts(.*)[\\/]/,
                        chunks: "initial",
                        priority: 17,
                    },
                    // 剩下的别忘记单独抽离
                    libs: {
                        name: "chunk-libs-vendors",
                        test: /[\\/]node_modules[\\/]/,
                        priority: 1, // 权重最低,优先考虑前面内容
                        chunks: "initial",
                    },

                    // 针对自己写的代码,重复使用的满足下面的配置就会抽离出来单独打包,比如 utils 下面的包
                    default: {
                        // 其他没有写的配置会使用上面的默认值
                        test: /[\\/]src(.*)[\\/]/,
                        name: "common-chunk",
                        minSize: 20000, // 超过 20kb,就会拆包
                        minChunks: 2,  // 引用两次就会拆包
                        priority: -10,
                        reuseExistingChunk: true
                    }
                }
            }
        },

        // 配置别名
        resolve: {
            alias: {
                "#": path.resolve(__dirname, "src")
            }
        },


        plugins: [
            new BundleAnalyzer({
                analyzerMode: 'server',
                analyzerHost: '127.0.0.1',
                analyzerPort: 8088,
                reportFilename: 'report.html',
                defaultSizes: 'parsed',
                openAnalyzer: true,
                generateStatsFile: false,
                statsFilename: 'state.json',
                statsOptions: null,
                logLevel: 'info'
            })
        ]
    }
})

// 打包分析工具加了之后 启动需要加上:
 "build": "vue-cli-service build",
 "build:analyze": "cross-env NODE_ENV=production npm_config_report=true vue-cli-service build"

vite 优化


http://www.kler.cn/news/107943.html

相关文章:

  • 基于华为云 IoT 物联网平台实现家居环境实时监控
  • MySQL总结 (思维导图,常用)
  • Github的2FA验证问题的丝滑解决方案 ||(Verify your two-factor authentication (2FA) settings)
  • vmware17.0|ubuntu22.04.0 解决灰色Vmware Tool 无法重新安装和 无法和win11相互拖拽文件问题
  • 【EI会议征稿】 2024年遥感、测绘与图像处理国际学术会议(RSMIP2024)
  • IT行业变成了夕阳行业
  • 力扣1047删除字符串中的所有相邻重复项(java,栈解法)
  • 若依框架的使用+代码生成功能
  • Capacitor 打包 h5 到 Android 应用,uniapp https http net::ERR_CLEARTEXT_NOT_PERMITTED
  • PyCharm社区版安装
  • nodejs+vue全国公考岗位及报考人数分析
  • 读取Excel的工具类——ExcelKit
  • GLoRE:大型语言模型的逻辑推理能力探究
  • 薛定谔的猫重出江湖?法国初创公司AliceBob研发猫态量子比特
  • Redis(04)| 数据结构-压缩列表
  • 汽车托运放坑小攻略
  • STM32 CAN使用
  • 【QT】信号和槽能自动传递参数
  • J2EE项目部署与发布(Windows版本)->会议OA单体项目Windows部署,spa前后端分离项目Windows部署
  • c++ 小案例:判断质数猜数字用符号填补心形图案
  • ​Vue3响应式原理
  • git clone失败
  • 《HelloGitHub》第 91 期
  • Flutter笔记:完全基于Flutter绘图技术绘制一个精美的Dash图标(中)
  • FFmpeg5.1.3编译动态库踩坑之旅(基于Linux虚拟机)
  • Ps:对象选择工具
  • 【torch高级】一种新型的概率学语言pyro(01/2)
  • PHP聊天系统源码 在线聊天系统网站源码 后台自适应PC与移动端
  • 2 第一个Go程序
  • 【Git推送本地项目到远程仓库】