問題描述
我已經嘗試了一天來編寫兩個管道函數,一個編譯更少的文件,另一個連接這些文件.我想學習如何為更復雜的插件編寫轉換流/管道.
I've been trying for a day to write two pipe functions, one that compiles less files and another one that concats these files. I want to learn how to write transform streams/pipes for more complex plugins.
所以我想知道如何從另一個管道讀取數據,以及如何更改該數據并將其發送到下一個管道.這是我目前所擁有的:
So I want to know how to read data from another pipe, and how to alter that data and send it to the next pipe. This is what I have so far:
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();
}))
我無法為第二個管道中的每個文件獲取 outputCSS
.如何發送?
I can't get the outputCSS
for each file in the second pipe. How can I send it?
推薦答案
好了,這里你不需要使用 fs
,你已經得到了文件流(這里是你的 chunk
).
Well, you don't need to use fs
here, you already got the stream of file (here your chunk
).
另一點,您沒有將文件發送回管道,所以我想這就是為什么在您的第二個文件上沒有調用任何內容的原因.
Another point, you're not sending back to the pipe the files, so I guess that's why nothing is called on your second one.
const through = require('through2')
gulp.src(sources)
.pipe(through.obj((chunk, enc, cb) => {
console.log('chunk', chunk.path) // this should log now
cb(null, chunk)
}))
在 ES2015 中:
In ES2015:
import through from 'through2'
gulp.src(sources)
.pipe(through.obj((chunk, enc, cb) => cb(null, chunk)))
對于你的具體例子:
.pipe(through.obj((file, enc, cb) => {
less.render(file.contents, { filename: file.path, ... }) // add other options
.then((res) => {
file.contents = new Buffer(res.css)
cb(null, file)
})
}))
這仍然很基本,我不檢查錯誤,如果它不是流等等,但這應該會給你一些關于你錯過了什么的提示.
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.
這篇關于如何編寫一個簡單的 gulp 管道函數?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!