Gulp 生態豐富,但有時需求獨特,自行開發外掛其實不複雜。核心在於實作一個轉換串流 (Transform Stream),接收 Vinyl 檔案物件,處理內容後推送下游。常用 through2 或封裝過的 through-gulp 簡化開發。
將 HTML 檔案中所有 {{something}} 替換為 Monkey 2 Dorie。
'use strict';
const through2 = require('through2');
module.exports = function modify() {
return through2.obj(function(file, encoding, cb) {
if (file.isNull()) { this.push(file); return cb(); }
if (file.isStream()) { this.emit('error', new PluginError('modify', 'Stream not supported')); return cb(); }
const content = file.contents.toString().replace(/{{something}}/g, ' Monkey 2 Dorie ');
file.contents = Buffer.from(content);
this.push(file);
cb();
});
};
'use strict';
const through = require('through-gulp');
module.exports = function modify() {
return through(function(file, encoding, callback) {
if (file.isNull()) { this.push(file); return callback(); }
if (file.isStream()) { this.emit('error', new PluginError('modify', 'Stream not supported')); return callback(); }
const content = file.contents.toString('utf-8').replace(/{{something}}/g, ' Monkey 2 Dorie ');
file.contents = Buffer.from(content, 'utf-8');
this.push(file);
callback();
}, function(callback) { // flush 階段
console.log('處理結束!');
callback();
});
};
Transform Stream 的函式。file.isNull() (直接推送) 與 file.isStream() (拋錯或轉換) 情況。Buffer 賦回 file.contents。through-gulp 提供 flush 回調,適合需要在串流結束時執行邏輯的場景。