如何编写简单的gulp管道功能?

Vla*_*ula 52 javascript node.js gulp

我一直在尝试编写两个管道函数,一个编译较少的文件,另一个编译这些文件.我想学习如何为更复杂的插件编写转换流/管道.

所以我想知道如何从另一个管道读取数据,以及如何更改该数据并将其发送到下一个管道.这是我到目前为止:

 gulp.src(sources)
   .pipe(through.obj(function (chunk, enc, cb) {

     var t = this;
     // console.log("chunk", chunk.path);
     fs.readFile(chunk.path, enc, function (err,data) {
       if (err) { cb(err); }

       less.render(data, {
         filename : chunk.path,
         sourceMap : {
           sourceMapRootpath : true
         }
       })
       .then(function (outputCss) {
          // console.log("less result",outputCss);
          t.push(chunk);// or this.push(outputCss) same result
          cb();
       });

     });

   }))
   .pipe(through.obj(function (chunk, enc, cb) {
     console.log("chunk", chunk.path); // not event getting called.
     cb();
   }))
Run Code Online (Sandbox Code Playgroud)

我无法获取outputCSS第二个管道中的每个文件.我该怎么发送?

Bal*_*zar 60

好吧,你不需要在fs这里使用,你已经得到了文件流(这里是你的chunk).

另一点,你不是要把文件送回管道,所以我猜这就是为什么你的第二个没有调用任何东西.

var through = require('through2')

gulp.src(sources)
  .pipe(through.obj(function (chunk, enc, cb) {
    console.log('chunk', chunk.path) // this should log now
    cb(null, chunk)
  }))
Run Code Online (Sandbox Code Playgroud)

在ES2015中:

import through from 'through2'

gulp.src(sources)
  .pipe(through.obj((chunk, enc, cb) => cb(null, chunk)))
Run Code Online (Sandbox Code Playgroud)

而对于您的具体示例:

.pipe(through.obj(function (file, enc, cb) {
  less.render(file.contents, { filename: file.path, ... }) // add other options
    .then(function (res) {
      file.contents = new Buffer(res.css)
      cb(null, file)
    })
}))
Run Code Online (Sandbox Code Playgroud)

This is still pretty basic, I don't check for errors, if it's not a stream and so on, but this should give you some hint on what you've missed.

  • @vsync我认为你正在越界.问题是关于如何编写简单的管道函数.我已经提供并回答了这个问题,如果你想知道gulp是如何工作的,你应该去他们的存储库.Stackoverflow是"唯一"您知道的问答网站. (12认同)
  • @vsync,你是否正在使用其他东西而不是"通过"?如果是这样,请写一个更好的答案.它将使我们所有人受益:) (6认同)
  • @vsync 简单_in gulp_,在不同的语言中可能会更容易 (2认同)