Gulp - 如何将属性传递给'lazypipe'函数?

时间:2016-03-12 07:44:22

标签: javascript gulp

所以我刚刚开始在一个项目中使用gulp,并且迄今为止喜欢它!我立即注意到我希望重新使用某些任务,但这个过程并不像我想象的那样直截了当。长话短说 - 我发现'lazypipe'是常见的方法。 但令人讨厌的是,我无法看到如何将属性传递给lazypipe函数。

我的原始代码:

gulp.task('scss', function () {
  return scss([sourceScss], { sourcemap: true, style: 'compact' })
    .on('error', function(err) {
        console.error('Error!', err.message);
    })
    .pipe(sourcemaps.init())
    .pipe(postcss([autoprefixer({ browsers: ['last 2 version'] })]))
    .pipe(minifyCSS())
    .pipe(rename('site.min.css'))
    .pipe(sourcemaps.write('.', { includeContent: false, sourceRoot: '../Styles'}))
    .pipe(gulp.dest(targetCss));
});

LAZY UPDATE:[...我希望将文件名传递给processSCSS]

var processSCSS = lazypipe()
    .pipe(sourcemaps.init)
    .pipe(postcss,[autoprefixer({ browsers: ['last 2 version'] })])
    .pipe(minifyCSS)
    .pipe(rename, "** fileName **")
    .pipe(sourcemaps.write, '.', { includeContent: false, sourceRoot: '../Styles' })
    .pipe(gulp.dest, './Styles/');

gulp.task('scss', function () {
    return scss(['./Styles/_themes/site.scss'], { sourcemap: true, style: 'compact' })
        .on('error', function(err) {
            console.error('Error!', err.message);
        })
        .pipe(processSCSS()); //pass fileName = 'site.min.css';
});

gulp.task('scssTheme', function () {
    return scss(['./Styles/_themes/bic.scss'], { sourcemap: true, style: 'compact' })
        .on('error', function(err) {
            console.error('Error!', err.message); 
        })
        .pipe(processSCSS()); //pass fileName = 'bic.min.css';
});

我相信这将是微不足道的,但我的技能目前还处于起步阶段:不幸的是,gulp和javascript一般都是如此。感谢任何想法/建议,非常感谢,PP

2 个答案:

答案 0 :(得分:0)

函数方法 bind 允许您使用在调用新函数时要提供的参数来创建函数。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind

要与lazypipe一起使用,请在gulp插件上调用bind并提供如下参数:

lazypipe()
  .pipe(processSCSS.bind(null, 'site.min.css'))

在这种情况下,我们不需要“ this”引用(bind的第一个参数),因此我们传递null。

答案 1 :(得分:0)

这里的问题是lazypipe需要一个函数作为参数,而不是一个函数的结果,因此您不能只编写processSCSS **()**,因为那样会执行它!

有一些选项可以包含额外的参数:bind显然可以正常工作(一种正常的JS功能,与插件无关)-但是基于插件的编写方式,这两种方法也都可以工作。

lazypipe()
  .pipe(processSCSS, 'site.min.css')

或者,如果您愿意(或有很多参数):

lazypipe()
  .pipe(function () {
    return processSCSS('site.min.css');
  });