在我的大肚子里.js,我希望能够根据使用gulp插件"gulp sharp responsive"的图像大小调整/压缩任务所占屏幕的近似百分比来计算宽度.

例如,我的一个全屏图像尺寸是1200.对于1/4宽度的图像,我希望它输出一个300px的图像?我希望避免手动计算新的宽度,并能够将除数设置为命令行选项,因此这是我在本教程之后提出的解决方案,https://www.sitepoint.com/pass-parameters-gulp-tasks/.

在gulpfile的顶部.js,我添加了以下代码:

// fetch command line arguments
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) {
            // argument value
            if (curOpt) arg[curOpt] = opt;
            curOpt = null;
        }
        else {

            // argument name
            curOpt = opt;
            arg[curOpt] = true;
        }
    }
    return arg;
})(process.argv);

我将div指定为arg.如果arg为null到1(即div=arg.d | | 1),则提供回退.注意,由于我主要是在全屏幕上以576px及以下的宽度(移动屏幕)显示特色图像,所以我没有用除数除以xs大小.此外,由于gulp sharp responsive无法处理非整数宽度,因此我必须使用舍入函数对商进行舍入.我的问题是,我该如何减少代码的冗余——例如,这样我就不会重复数学了.每个常量变量的round().如果你有任何建议,使我的代码更简洁,请让我知道,我只是一个初学者.谢谢

function sharpImg() {
    const div = arg.d || 1, xs = (Math.round(576 / div)), sm = (Math.round(769 / div)), md = (Math.round(992 / div)), lg = (Math.round(1200 / div)), xl = (Math.round(1400 / div)), xxl = (Math.round(2048 / div));
    return src(['_images/original/process/**/*.{jpeg,jpg,png,tiff,webp}', '!_images/original/raw/**'])
        .pipe($.rename(function (path) {
            path.dirname += "/" + path.basename;
        }))
        .pipe($.sharpResponsive({
            formats: [
                // jpeg
                { width: xs, format: "jpeg", rename: { suffix: "-xs" }, jpegOptions: { quality: 50, progressive: true } },
                { width: sm, format: "jpeg", rename: { suffix: "-sm" }, jpegOptions: { quality: 50, progressive: true } },
                { width: md, format: "jpeg", rename: { suffix: "-md" }, jpegOptions: { quality: 50, progressive: true } },
                { width: lg, format: "jpeg", rename: { suffix: "-lg" }, jpegOptions: { quality: 50, progressive: true } },
                { width: xl, format: "jpeg", rename: { suffix: "-xl" }, jpegOptions: { quality: 50, progressive: true } },
                { width: xxl, format: "jpeg", rename: { suffix: "-xxl" }, jpegOptions: { quality: 50, progressive: true } },
                // webp
                { width: xs, format: "webp", rename: { suffix: "-xs" }, webpOptions: { quality: 50 } },
                { width: sm, format: "webp", rename: { suffix: "-sm" }, webpOptions: { quality: 50 } },
                { width: md, format: "webp", rename: { suffix: "-md" }, webpOptions: { quality: 50 } },
                { width: lg, format: "webp", rename: { suffix: "-lg" }, webpOptions: { quality: 50 } },
                { width: xl, format: "webp", rename: { suffix: "-xl" }, webpOptions: { quality: 50 } },
                { width: xxl, format: "webp", rename: { suffix: "-xxl" }, webpOptions: { quality: 50 } },
                // avif
                { width: xs, format: "avif", rename: { suffix: "-xs" }, avifOptions: { quality: 50 } },
                { width: sm, format: "avif", rename: { suffix: "-sm" }, avifOptions: { quality: 50 } },
                { width: md, format: "avif", rename: { suffix: "-md" }, avifOptions: { quality: 50 } },
                { width: lg, format: "avif", rename: { suffix: "-lg" }, avifOptions: { quality: 50 } },
                { width: xl, format: "avif", rename: { suffix: "-xl" }, avifOptions: { quality: 50 } },
                { width: xxl, format: "avif", rename: { suffix: "-xxl" }, avifOptions: { quality: 50 } },
            ]
        }))
        .pipe(dest('_images/processed'))
}

导出任务:

exports.sharpImg = sharpImg;

结果:

推荐答案

您可以创建一个断点对象,一个用于重复计算的函数.在划分的基础上,再加上一些现代的JS majicks,我认为你的代码可以更短,更少的重复,但同样可读,更重要的是,很容易更改断点,例如

function sharpImg() {
    const BREAKPOINTS = {
        xs: 576,
        sm: 769,
        md: 992,
        lg: 1200,
        xl: 1400,
        xxl: 2048,
    };
    const onDiv = div => Object.entries(BREAKPOINTS).map(([bp, value]) => [Math.round(value / div), `-${bp}`]);
    // creates an array of [[1, "-xs"], [2, "-sm"], ... ] (obviously the values are 576/div etc)
    
    const div = arg.d || 1, bps = onDiv(div);
    
    const jpegOptions = { quality: 50, progressive: true };
    const webpOptions = { quality: 50 };
    const avifOptions = { quality: 50 };
    
    return src(['_images/original/process/**/*.{jpeg,jpg,png,tiff,webp}', '!_images/original/raw/**'])
        .pipe($.rename(function (path) {
            path.dirname += "/" + path.basename;
        }))
        .pipe($.sharpResponsive({
            formats: [
                // jpeg
                ...bps.map(([width, suffix]) => ({ width, format: "jpeg", rename: { suffix }, jpegOptions })),
                // webp
                ...bps.map(([width, suffix]) => ({ width, format: "webp", rename: { suffix }, webpOptions })),
                // avif
                ...bps.map(([width, suffix]) => ({ width, format: "avif", rename: { suffix }, avifOptions })),
            ]
        }))
        .pipe(dest('_images/processed'))
}

输出format以判断其是否正确的代码段

function sharpImg() {
    const BREAKPOINTS = {
        xs: 576,
        sm: 769,
        md: 992,
        lg: 1200,
        xl: 1400,
        xxl: 2048,
    };
    const onDiv = div => Object.entries(BREAKPOINTS).map(([bp, value]) => [Math.round(value / div), `-${bp}`]);
    // creates an array of [[1, "-xs"], [2, "-sm"], ... ] (obviously the values are 576/div etc)
    
    const div = 1, bps = onDiv(div);
    
    const jpegOptions = { quality: 50, progressive: true };
    const webpOptions = { quality: 50 };
    const avifOptions = { quality: 50 };
    const formats = [
        // jpeg
        ...bps.map(([width, suffix]) => ({ width, format: "jpeg", rename: { suffix }, jpegOptions })),
        // webp
        ...bps.map(([width, suffix]) => ({ width, format: "webp", rename: { suffix }, webpOptions })),
        // avif
        ...bps.map(([width, suffix]) => ({ width, format: "avif", rename: { suffix }, avifOptions })),
    ];
    return formats;
}
console.log(JSON.stringify(sharpImg(), null, 4));

Javascript相关问答推荐

Cypress -使用commands.js将数据测试id串在一起失败,但在将它们串在一起时不使用命令有效

docx.js:如何在客户端使用文档修补程序

Angular 17—每当一个布尔变量变为真时触发循环轮询,只要它保持为真

colored颜色 检测JS,平均图像 colored颜色 检测JS

使用Java脚本根据按下的按钮更改S文本

使用POST请求时,Req.Body为空

ChartJs未呈现

rxjs插入延迟数据

Web Crypto API解密失败,RSA-OAEP

使用getBorbingClientRect()更改绝对元素位置

将异步回调转换为异步生成器模式

是否可以在Photoshop CC中zoom 路径项?

如果一个字符串前面有点、空格或无字符串,后面有空格、连字符或无字符串,则匹配正则表达式

使用自动识别发出信号(&Q)

处理TypeScrip Vue组件未初始化的react 对象

Pevent触发material 用户界面数据网格中的自动保存

MongoDB通过数字或字符串过滤列表

如何在每隔2分钟刷新OKTA令牌后停止页面刷新

如何使用useparams从react路由中提取id

如何在底部重叠多个div?