简体   繁体   中英

Generate Critical CSS for every *.HTML file using critical and Gulp

Ok, I have been pulling my hair out for the past day trying to figure this out. I am trying to generate critical CSS for every HTML file in my directory. My current working code that runs fine on a single file:

export const criticalCSS = () => {
  return critical.generate({
    inline: true,
    base: '_dist',
    src: 'index.html',
    css: '_dist/index.css',
    width: 960,
    height: 600,
    dest: 'index.html',
    extract: true,
    ignore: ['@font-face']
  })
}

Normally I should expect the src to accept an array of file paths and from what I can see on every grunt tutorials this is the case for the grunt plugin. However, I can't get it working on gulp. I have seen some posts suggesting gulp-foreach but this also does not seem to work.

ForEach example:

export const criticalCSS = () => {
  return gulp.src(paths.html.src).pipe(
    foreach(function (stream, file) {
      return stream.pipe(
        critical.generate({
          inline: true,
          base: '_dist',
          src: file.path,
          css: '_dist/index.css',
          width: 960,
          height: 600,
          dest: file.path,
          extract: true,
          ignore: ['@font-face']
        })
      )
    })
  )
}

Has anyone got this working? The only other thing I can imagine is hardcoding an array with every HTML file path and then looping through them passing the critical.generate function. However, this will not be maintainable if I have to manually specify every HTML file.

If you are using the library critical .

I have been having success like this:

var critical = require('critical').stream;
gulp.task('html-inline-critical', function () {
return gulp.src('public/**/*.html', {base: './'})
    .pipe(
        critical({
            base: 'public/',
            inline: true,
            css: [
                'public/c/css/main.css'
            ],
            dimensions: [
                {height: 720, width: 1280}
            ],
            minify: true,
            timeout: 120000
        });
    )
    .on('error', function(err) { 
        gutil.log(gutil.colors.red(err.message)); 
    })
    .pipe(gulp.dest('./'));
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM