2016-08-15 17 views
0

我試圖編寫一個函數,讓你使用任何插件插件作爲一個簡單的內存緩衝區變壓器(隱藏所有的流/乙烯基材料)。例如,它可以被稱爲是這樣的:如何通過gulp插件運行緩衝區?

const gulpMinifyHtml = require('gulp-minify-html'); 

transformBufferWithGulpPlugin(inputBuffer, gulpMinifyHtml()).then(outputBuffer => { 
    // outputBuffer should now be a minified version of inputBuffer 
}); 

(注:我正在尋找一種通用的方法來做到這一點與任何一飲而盡插件;吞掉,縮小HTML的只是一個例子。)


看起來好像很容易,但我正在試圖讓它工作。我想我需要做的是:

  1. 構造一個新的Vinyl實例與設置爲inputBuffer
  2. 把這種乙烯基實例爲對象流
  3. 管通過吞氣插件對象流內容(?)
  4. 從流中收集輸出
  5. 當流完成輸出後,從乙烯實例中抓取內容緩衝區,並用它來解決。

這些步驟基本正確嗎?任何人都可以向我展示一個工作示例,或者指向我的模塊嗎?

回答

1

以下應該工作。這使用stream-array來創建流。

var File = require('vinyl'); 
var streamify = require('stream-array'); 

function transformBufferWithGulpPlugin(inputBuffer, gulpPlugin) { 
    return new Promise(function(resolve, reject) { 
    streamify([new File({path:'dummy', contents:inputBuffer})]) 
     .pipe(gulpPlugin) 
     .on('error', reject) 
     .on('data', function(file) { 
     resolve(file.contents); 
    }); 
    }); 
} 

var minify = require('gulp-html-minify'); 

transformBufferWithGulpPlugin(new Buffer('<p>\n Test \n</p>'), minify()) 
    .then(function(result) { 
    console.log(result.toString()); 
    }, function(error) { 
    console.error(error); 
    }); 

這不是絕對必要指定虛擬path爲我做以上(vinyl不要求),但如果有一個path屬性一些插件可能只工作。

+0

謝謝,這對我測試過的一個插件很有用([gulp-template](https://github.com/sindresorhus/gulp-template)),但不適用於其他人([gulp-autoprefixer](https:// github.com/sindresorhus/gulp-autoprefixer),[gulp-clean-css](https://github.com/scniro/gulp-clean-css)等)。在非工作示例中,數據事件觸發OK,但傳遞給'resolve'的'file.contents'似乎包含原始未轉換的源。你能想出任何可能的原因嗎?我已經使用相同的選項驗證了這些插件在常規gulp文件中的工作。 – callum

+0

試用了這兩個插件。工作正常。 –

+0

嗯好吧,我會再試一次 – callum