Gulp:将srcset属性添加到所有img标记

xwbd5t1u  于 2022-12-08  发布在  Gulp
关注(0)|答案(1)|浏览(159)

我正在使用gulpjekyll构建一个站点,我正在尝试设置gulpfile,以便它自动浏览所有的html文件,并添加srcset信息以进行响应图像交付。
基本上,我想把这个:

<img src="/img/agency/agency-lobby.jpg" />

导入此文件(对于HTML文件中的每个图像):

<img src="/img/agency/agency-lobby.jpg" srcset="/img/agency/agency-lobby400.jpg 400w, /img/agency/agency-lobby600.jpg 600w, /img/agency/agency-lobby900.jpg 900w, /img/agency/agency-lobby900.jpg 1200w, /img/agency/agency-lobby1800.jpg 1800w"/>

我的gulpfile显然被配置为执行许多自动化任务,其中之一是查看unsized-img文件夹,并为我设置的每个断点创建图像大小,然后将其输出到img文件夹 (我这样做是为了避免Jekyll只使用原始图像覆盖我的*_sites/img文件夹)*。然后,我有一个优化任务,将优化所有这些图像的最终输出在_sites/img**文件夹。
现在我想让gulp检查并找到所有的img标签,并自动化它,这样它就可以为每个图像添加srcset属性,这样我就不必每次都用5个srcset属性手动写入每个图像。

var gulp        = require('gulp');
var browserSync = require('browser-sync');
var sass        = require('gulp-sass');
var prefix      = require('gulp-autoprefixer');
var cp          = require('child_process');
var cleanCSS    = require('gulp-clean-css');
var uglify      = require('gulp-uglify');
var pump        = require('pump');
var imagemin    = require('gulp-imagemin');
var imageresize = require('gulp-image-resize');
var rename      = require("gulp-rename");

var jekyll   = process.platform === 'win32' ? 'jekyll.bat' : 'jekyll';
var messages = {
    jekyllBuild: '<span style="color: grey">Running:</span> $ jekyll build'
};

/**
 * Build the Jekyll Site
 */
gulp.task('jekyll-build', function (done) {
    browserSync.notify(messages.jekyllBuild);
    return cp.spawn( jekyll , ['build'], {stdio: 'inherit'})
        .on('close', done);
});

/**
 * Rebuild Jekyll & do page reload
 */
gulp.task('jekyll-rebuild', ['jekyll-build'], function () {
    browserSync.reload();
});

/**
 * Wait for jekyll-build, then launch the Server
 */
gulp.task('browser-sync', ['sass', 'jekyll-build'], function() {
    browserSync({
        server: {
            baseDir: '_site'
        }
    });
});

/**
 * Compile files from _scss into both _site/css (for live injecting) and site (for future jekyll builds)
 */
gulp.task('sass', function () {
    return gulp.src('_scss/main.scss')
        .pipe(sass({
            includePaths: ['scss'],
            onError: browserSync.notify
        }))
        .pipe(prefix(['last 15 versions', '> 1%', 'ie 8', 'ie 7'], { cascade: true }))
        .pipe(cleanCSS({compatibility: 'ie8'}))
        .pipe(gulp.dest('_site/css'))
        .pipe(browserSync.reload({stream:true}))
        .pipe(gulp.dest('css'));
});

/**
 * Minify javascript files (must be run separatly after gulp)
 */
gulp.task('compress', function(cb){
  pump([
        gulp.src('js/*.js'),
        uglify(),
        gulp.dest('_site/js')
    ],
    cb
  );
});

/**
 * Compress image files
 */

   var resizeImageTasks = [];
   [400,600,900,1200,1800].forEach(function(size) {
     var resizeImageTask = 'resize_' + size;
     gulp.task(resizeImageTask, function() {
         gulp.src('unsized-img/**/*.{jpg,png,gif}')
             .pipe(imageresize({
               width: size,
               upscale: false,
             }))
             .pipe(rename(function (path) { path.basename += size; }))
             .pipe(gulp.dest('img'));
           gulp.src('img/**/*.{svg,ico}')
            .pipe(gulp.dest('img'));
     });
     resizeImageTasks.push(resizeImageTask);
   });

gulp.task('resize', resizeImageTasks);

gulp.task('optimize', function() {
    gulp.src('img/**/*.{jpg,png,gif}')
        .pipe(imageresize({
          quality: 0.8,
          samplingFactor: [2, 2],
          noProfile: true,
          interlace: true,
        }))
        .pipe(imagemin())
        .pipe(gulp.dest('_site/img'));
      gulp.src('img/**/*.{svg,ico}')
       .pipe(gulp.dest('_site/img'));
});
/**
 * Watch scss files for changes & recompile
 * Watch html/md files, run jekyll & reload BrowserSync
 */
gulp.task('watch', function () {
    gulp.watch('_scss/*.scss', ['sass']);
    gulp.watch(['*.html', '_layouts/*.html', '_posts/*', 'work/*.html', 'services/*.html', 'culture/*.html', 'blog/*.html', 'contact/*.html', 'agency/*.html', 'blog/**/*.md','work/**/*.md'], ['jekyll-rebuild']);
});

/**
 * Default task, running just `gulp` will compile the sass,
 * compile the jekyll site, launch BrowserSync & watch files.
 */
gulp.task('default', ['browser-sync', 'watch']);
fcwjkofz

fcwjkofz1#

看起来你可能是在gulp插件gulp-srcset-lazy(https://www.npmjs.com/package/gulp-srcset-lazy)后,这显然是一个克隆的现在不活跃的gulp-img-retina插件。
它处理流,将srcset attr插入到所有图像标签中(注意,它当前忽略SVG),并使用选项确定要添加的分辨率或宽度以及要应用的后缀。
在您的情况下,我不知道Jekyll构建是如何工作的,但我认为您可以在将HTML发送到构建过程之前对其进行预处理。

import srcset from 'gulp-srcset-lazy';  

let srcSetOpts = {
    suffix: {
        '480w': '@480w.jpeg',
        '960w': '@960w.jpeg',
        '1440w': '@1440w.jpeg',
        '1920w': '@1920w.jpeg',
     }
};

gulp.src(inputPath)
    .pipe( srcset(srcSetOpts ) )
    .pipe( gulp.dest(outputPath) )
    .pipe( connect.reload() );

转换

<img src="images/title_bg.jpeg" alt="title background" 
    loading=lazy>

进入

<img alt="title background" loading="lazy" data-format=".jpeg" 
    data-src="images/title_bg.jpeg" 
    data-srcset="images/title_bg@480w.jpeg 480w, images/title_bg@960w.jpeg 960w, 
    images/title_bg@1440w.jpeg 1440w, images/title_bg@1920w.jpeg 1920w">

相关问题