0

我正在尝试编写一个 gulp 插件watchify,以便我将文件通过管道传输到其中。问题是我的任务从未真正“完成”,因为它坐在那里并监视一堆文件并根据需要重新构建。

那么如何“通过”这个插件发送代码呢?

现在,我调用插件的任务被简化为:

gulp.src( '/path/to/js/*.js' )
    .pipe( watchifyPlugin() )
    .pipe( cfg.gulp.dest( '/path/to/build' ) )

watchifyPlugin的是:

module.exports = function( opts ){
    return through.obj( function( file, enc, cb ){
        // watchify file
        self.push( data ); // whenever any .js files are updated

        // never call cb()
    }
}

现在这适用于.js我的 glob 找到的第一个文件。但是,任何其他文件实际上都不会到达我的插件,我假设这是因为我从不调用cb().

那么我该怎么做呢?有没有办法在不调用的情况下继续写入流cb(),这会关闭它,但仍然允许以前的管道继续?

换句话说:

  • index.js
    • watchify()
    • 管道dest()很好,即使我self.push()一次又一次地打电话
    • cb()从来没有打电话
  • index2.js
    • watchify()在被要求之前从不调用cb()index.js但这会“关闭”index.js管道
4

2 回答 2

0

这是一个非常糟糕的主意。并非 gulp 中的所有内容都必须是插件,尤其是 browerify 和 watchify 插件一直被禁止。(参见https://github.com/gulpjs/plugins/blob/master/src/blackList.json。)如果要运行 watchify,直接使用 watchify 即可。从https://github.com/gulpjs/gulp/blob/master/docs/recipes/fast-browserify-builds-with-watchify.md

var gulp = require('gulp');
var source = require('vinyl-source-stream');
var watchify = require('watchify');

gulp.task('watch', function() {
  var bundler = watchify('./src/index.js');

  // Optionally, you can apply transforms
  // and other configuration options on the
  // bundler just as you would with browserify
  bundler.transform('brfs');

  bundler.on('update', rebundle);

  function rebundle () {
    return bundler.bundle()
      .pipe(source('bundle.js'))
      .pipe(gulp.dest('./dist'))
  }

  return rebundle();
});
于 2014-06-18T09:48:42.860 回答
0

您以错误的方式使用 through,您必须在处理完文件后调用回调(“数据”事件)。然而,它并没有cb()关闭流,它end甚至发出了这样做的。

您可以延迟结束事件并继续调用this.push以发送新文件。

就像是

var Through = require('through2').obj;
var my_plugin = function() {

  var last_file = null; // as an example, last emitted file

  function handle_data = function(file, enc, done) { 
    this.push(file); // emit the file
    this.push(file); // just for kicks, emit it again
    last_file = file;
    done(); // done handling *this* file
  }

  function handle_end = function(done) {
     if(last_file) this.push(last_file); // emit the last file again
     done(); // handled the 'end' event
  }

  return Through(handle_data, handle_end);
}

这将在处理下一个文件之前发出每个文件两次,然后当它处理完所有文件(end收到事件)时,它会再次发出最后一个文件,然后发出end事件。

但是,当某些事情发生变化时,您为什么不使用gulp.watch而只是再次运行任务呢?甚至使用gulp-watch插件,它在文件更改时发出文件?

于 2014-06-18T09:15:30.890 回答