如何编写简单调用函数的Gulp任务

J. *_*Doe 5 javascript node.js gulp

我正在努力创建一个除了调用自定义函数之外什么都不做的Gulp任务.不,我有,没有源文件,不,我没有目标文件.我只想在独立任务中调用自定义函数,因此我可以根据它来执行其他任务.

为了爱我,我检查了谷歌和SO,我找不到一个例子.我最接近的就是这个

var through = require('through2');

gulp.task(
    'my-custom-task',
    function ()
    {
        return through.obj(
            function write(chunk, enc, callback) {
                // here is where the custom function is called
                myCustomFunction('foo', 'bar');
                callback(null, chunk);
            }
        );
    }
);
Run Code Online (Sandbox Code Playgroud)

现在这确实调用了myCustomFunction,但是当我运行任务时gulp my-custom-task,我可以看到任务开始但没有完成.

[10:55:37] Starting 'clean:tmp'...
[10:55:37] Finished 'clean:tmp' after 46 ms
[10:55:37] Starting 'my-custom-task'...
Run Code Online (Sandbox Code Playgroud)

我应该如何正确地编写我的任务?

pok*_*oke 7

如果您只想要一个运行某些功能的任务,那么就这样做:

gulp.task('my-custom-task', function () {
    myCustomFunction('foo', 'bar');
});
Run Code Online (Sandbox Code Playgroud)

如果你的函数异步执行某些操作,它应该在最后调用一个回调,所以gulp能够知道它何时完成:

gulp.task('my-custom-task', function (callback) {
    myCustomFunction('foo', 'bar', callback);
});
Run Code Online (Sandbox Code Playgroud)

至于为什么你的解决方案不起作用,使用through是一种使用流的方法.您可以使用它来创建可以.pipe()进入gulp流的处理程序.由于您实际上没有使用gulp流,因此您无需创建流处理程序和/或通过此处使用.