webpack优化构建体积示例-并行压缩:

发布于:2024-05-16 ⋅ 阅读:(192) ⋅ 点赞:(0)

uglifyjs-webpack-plugin和terser-webpack-plugin都可以开启多进程并进行压缩来减小构件体积大小。
当在 Webpack 配置中启用 minimize: true 时,构建时间通常会增加,这是因为 Webpack 会在构建过程中添加一个额外的步骤:代码压缩。代码压缩是一个资源密集型的任务,它需要分析代码,移除不必要的字符、空格、注释,以及应用各种优化策略来减小最终打包文件的体积。

webpack.config.js
const config = {
    entry: './src/index.js',
    output: {
        filename: 'main.js'
    },
  mode: 'development',  
}

module.exports = config;
src/index.js
import {otherSomeFuction} from './module';  
  
console.log(otherSomeFuction());

import $ from 'jquery'

$(document).ready(() => {
    $('body').css({
        width: '100%',
        height: '100%',
        'background-color': 'red'
    })
})
src/module.js
export const otherSomeFuction= () => {
    console.log('otherSomeFuction...')
}

构建前体积
在这里插入图片描述
构建后体积

webpack.config.js

const TerserPlugin = require('terser-webpack-plugin');  

const config = {
    entry: './src/index.js',
    output: {
        filename: 'main.js'
    },
  mode: 'development',
  optimization: {  
    minimize: true, // 告诉webpack开启压缩  
    minimizer: [  
      new TerserPlugin({  
      // sourceMap: ifProduction(false, true), // if prod, disable it, otherwise enable
        // parallel: true,
        // 这里可以配置 Terser 的选项  
        // 例如,你可以设置 terserOptions 来控制 Terser 的压缩行为  
        terserOptions: {  
          compress: {  
            drop_console: true, // 删除所有的 `console` 语句  
            // 其他 Terser 压缩选项...  
          },  
        },  
        // 注意:这里没有直接控制多进程的选项  
        // 但是 Webpack 和 TerserWebpackPlugin 可能会根据 Node.js 的环境自动使用多核  
      }),  
    ],  
  },  
}

module.exports = config;

在这里插入图片描述

可以看到构建产物减小了 321-316=5kb


网站公告

今日签到

点亮在社区的每一天
去签到