使用critical和Gulp为每个* .HTML文件生成关键CSS

时间:2018-03-17 14:22:54

标签: javascript gulp

好的,过去一天我一直在拔头发试图解决这个问题。我正在尝试为我的目录中的每个HTML文件生成关键的CSS。我当前的工作代码在单个文件上运行良好:

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

通常我应该期望src接受一个文件路径数组,并且从我在每个grunt教程中看到的内容都是grunt插件的情况。但是,我无法在gulp上工作。我已经看到一些帖子暗示了gulp-foreach,但这似乎也不起作用。

ForEach示例:

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

有人有这个工作吗?我能想象的另一件事就是用每个HTML文件路径对数组进行硬编码,然后通过它们循环传递critical.generate函数。但是,如果我必须手动指定每个HTML文件,这将无法维护。

1 个答案:

答案 0 :(得分:1)

如果您使用的是库critical

我一直在成功:

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('./'));
});