You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

gulpfile.js中批量对常量取整的代码精简优化方案

gulp图片处理任务精简优化方案

优化思路

现有代码的冗余主要来自两部分:重复的断点宽度计算、重复的输出格式规则定义,把可变的配置项抽离统一处理,用循环生成重复结构即可,不需要逐条手写规则。
核心优化点:

  • 把断点宽度、输出格式、压缩参数都抽成独立配置项,后续调整参数只需要改配置区,不用动核心逻辑
  • 统一处理宽度计算逻辑,只需要写一次Math.round,同时单独适配xs断点不随除数缩放的特殊规则
  • 自动生成所有格式+断点的组合规则,避免手写十几条结构完全相同的配置
  • 对命令行传入的除数参数做显式数字转换,避免字符串运算的隐式类型转换问题

优化后完整代码

保留原有命令行参数解析代码,替换sharpImg任务部分即可:

// 原有命令行参数解析代码保留
const arg = (argList => {
    let arg = {}, a, opt, thisOpt, curOpt;
    for (a = 0; a < argList.length; a++) {
        thisOpt = argList[a].trim();
        opt = thisOpt.replace(/^\-+/, '');
        if (opt === thisOpt) {
            if (curOpt) arg[curOpt] = opt;
            curOpt = null;
        }
        else {
            curOpt = opt;
            arg[curOpt] = true;
        }
    }
    return arg;
})(process.argv);

function sharpImg() {
  // ========== 配置区 后续调整参数只改这里 ==========
  const TASK_CONFIG = {
    defaultDivisor: 1, // 默认除数
    // 断点配置,scaleWithDivisor标记是否随传入的除数缩放
    breakpoints: [
      { name: 'xs', baseWidth: 576, scaleWithDivisor: false },
      { name: 'sm', baseWidth: 769, scaleWithDivisor: true },
      { name: 'md', baseWidth: 992, scaleWithDivisor: true },
      { name: 'lg', baseWidth: 1200, scaleWithDivisor: true },
      { name: 'xl', baseWidth: 1400, scaleWithDivisor: true },
      { name: 'xxl', baseWidth: 2048, scaleWithDivisor: true }
    ],
    // 输出格式配置,新增格式直接加条目
    outputFormats: [
      { format: 'jpeg', optionsKey: 'jpegOptions', options: { quality: 50, progressive: true } },
      { format: 'webp', optionsKey: 'webpOptions', options: { quality: 50 } },
      { format: 'avif', optionsKey: 'avifOptions', options: { quality: 50 } }
    ]
  }

  // ========== 逻辑区 一般不需要修改 ==========
  // 计算实际使用的除数,显式转数字避免类型问题
  const div = Number(arg.d) || TASK_CONFIG.defaultDivisor;
  // 统一计算所有断点的实际输出宽度
  const widthMap = {};
  TASK_CONFIG.breakpoints.forEach(bp => {
    const rawWidth = bp.scaleWithDivisor ? bp.baseWidth / div : bp.baseWidth;
    widthMap[bp.name] = Math.round(rawWidth);
  });

  // 自动生成sharpResponsive需要的formats配置
  const formats = [];
  TASK_CONFIG.outputFormats.forEach(fmt => {
    TASK_CONFIG.breakpoints.forEach(bp => {
      formats.push({
        width: widthMap[bp.name],
        format: fmt.format,
        rename: { suffix: `-${bp.name}` },
        [fmt.optionsKey]: fmt.options
      })
    })
  });

  // 原有任务执行逻辑不变
  return src(['_images/original/process/**/*.{jpeg,jpg,png,tiff,webp}', '!_images/original/raw/**'])
    .pipe($.rename(function (path) {
      path.dirname += "/" + path.basename;
    }))
    .pipe($.sharpResponsive({ formats }))
    .pipe(dest('_images/processed'))
}

exports.sharpImg = sharpImg;

使用方式

和原有使用逻辑完全兼容:

  • 执行gulp sharpImg:使用默认除数1,输出预设全尺寸断点的图片
  • 执行gulp sharpImg --d 4:除xs断点外,所有宽度自动除以4取整,输出1/4屏宽适配的图片
    后续如果需要新增断点、调整压缩质量、新增输出格式(比如png),只需要在顶部TASK_CONFIG里加对应配置项即可,不需要重复写大段结构相同的代码。

内容的提问来源于stack exchange,提问作者Sam Miller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 20:42:19