gulpfile.js中JavaScript中const变量列表的更好方法?

发布于 2025-02-11 22:51:22 字数 3998 浏览 0 评论 0原文

在我的gulpfile.js中,我希望能够根据屏幕的大约百分比来计算宽度,它们将使用“ gulp-sharp响应性”的图像大小/压缩任务占用图像大小/压缩任务。

例如,我的全屏图像的尺寸之一是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.d,如果ARG为1(IE,Div = arg.d || 1),则提供了后备。请注意,由于我主要打算以576px及以下(移动屏幕)的全屏显示特色图像,因此我不会将XS大小除以除数。同样,由于Gulp-sharp响应性无法处理非整体宽度,因此我不得不使用圆形功能将商围起来。我的问题是,如何使我的代码减少冗余 - 例如,我不会重复每个const变量的Math.Round.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;

结果: 运行“ Gulp Sharpimg”会导致定义默认的const宽度,而运行“ Gulp Sharpimg -d 4”导致图像1/4的默认宽度。

In my gulpfile.js, I want to be able to calculate widths based on the approximate percentage of the screen that they will occupy for an image sizing/compression task using the gulp plugin "gulp-sharp-responsive".

For example, one of my sizes for a full-screen image is 1200. For images that are 1/4 that width, I want it to output a 300px image? I wanted to avoid having to manually calculate the new width and to be able to set the divisor as a command-line option, so this is the solution I came up with the below approach following this tutorial, https://www.sitepoint.com/pass-parameters-gulp-tasks/.

At the top of gulpfile.js, I added the following code:

// 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);

I assigned div as arg.d and provided a fallback if arg is null to 1 (i.e., div = arg.d || 1). Note, since I am mainly going to show featured images at full screen at widths 576px and below (mobile screens), I am not dividing the xs size by a divisor. Also since the gulp-sharp-responsive is not able to process non-integer widths, I had to round the quotient with the round function. My question is, how would I make my code less redundant--for example, so I am not repeating math.round() for each const variable. If you have any suggestions to make my code more succinct please let me know, I am just a beginner. Thanks!

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'))
}

export task:

exports.sharpImg = sharpImg;

The result:
Running "gulp sharpImg" results in the default const widths defined, whereas running "gulp sharpImg --d 4" results in images 1/4 their default width.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

清风疏影 2025-02-18 22:51:22

您可以创建一个断点对象,一个重复数学的函数。该部门的台面,然后使用一些现代的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'))
}

输出格式检查是否正确的摘要

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));

You could create a breakpoints object, a function to do the repetitive math.floor of the division, then with some modern JS majicks, I think your code can be a lot shorter, less repetitive, yet just as readable, and, importantly, easy to change the breakpoints for example

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'))
}

A snippet that outputs format to check if it's right

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));

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文