首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

手把手教你撰寫 Gulp 外掛 (以 through2 / through-gulp 為例)

     編輯:Java 相關知識

Gulp 生態豐富,但有時需求獨特,自行開發外掛其實不複雜。核心在於實作一個轉換串流 (Transform Stream),接收 Vinyl 檔案物件,處理內容後推送下游。常用 through2 或封裝過的 through-gulp 簡化開發。

需求場景

將 HTML 檔案中所有 {{something}} 替換為 Monkey 2 Dorie。

方案一:使用 through2

'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();
    });
};

方案二:使用 through-gulp

'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 回調,適合需要在串流結束時執行邏輯的場景。

擴展閱讀

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved