共享task: gulp registry
gulp的一个 task 共享机制 Registry
创建 Registry
允许将自定义注册表插入任务系统,该系统可以提供共享任务或增强功能。注册中心使用
registry()
.
模板
四个方法,缺一不可,否则: an error will be thrown.
- init: 接收一个 gulpInstance
- get: 根据 name 取得 task
- set: name/task 设置一个task 到
tasks = {}
的 map 中去 - tasks: 所有的
tasks
集合
// as a function
function TestRegistry() {}
TestRegistry.prototype.init = function (gulpInst) {}
TestRegistry.prototype.get = function (name) {}
TestRegistry.prototype.set = function (name, fn) {}
TestRegistry.prototype.tasks = function () {}
// as a class
class TestRegistry {
init(gulpInst) {}
get(name) {}
set(name, fn) {}
tasks() {}
}
使用 Registry
const { registry } = require('gulp');
// ... TestRegistry setup code
// good!
registry(new TestRegistry())
// bad!
registry(TestRegistry())
// This will trigger an error: 'Custom registries must be instantiated, but it looks like you passed a constructor'
我写的一个实例
- MyRegistry
- 基类:
UndertakerRegistry
const gulp = require("gulp");
const UndertakerRegistry = require("undertaker-registry");
const del = require("del");
class MyRegistry extends UndertakerRegistry {
constructor(opts) {
super(opts)
this.opts = opts || {};
this.buildDir = this.opts.buildDir || "./dist";
}
init(takerInst) {
const buildDir = this.buildDir;
takerInst.task("clean", function () {
return del([buildDir]);
});
}
}
const registry = new MyRegistry();
gulp.registry(registry);
列出 shared task
$ npx gulp -T
[22:03:14] Tasks for ~/Downloads/gulpfile.js
[22:03:14] └── clean
几个好用的基类
UndertakerRegistry
默认,只帮你写好了 get/set/tasks 这3个方法CommonTasks
: 提供了 clean/serve 这2个有用的task
var gulp = require('gulp');
var CommonTasks = require('undertaker-common-tasks');
gulp.registry(new CommonTasks({ port: 1337, buildDir: './dist' }));
// 'clean' & 'series' were defined by the registry
gulp.task('default', gulp.series('clean', 'serve'));
根据条件注册 pipe
https://stackoverflow.com/questions/27181719/gulp-condition-inside-pipe
gulp.task('task', function () {
let stream = gulp.src(sources.sass)
.pipe(changed(output.css)).pipe(sass({
style: 'compressed',
sourcemap: true
}));
if (2 + 2 === 4) {
stream = stream
.pipe(someModule())
.pipe(someModule2());
}
else {
stream = stream
.pipe(someModule3())
.pipe(someModule4());
}
stream = stream.pipe(notify('scss converted to css and compressed'));
return stream;
});
参考
- https://gulpjs.com/docs/en/advanced/creating-custom-registries/
- undertaker-registry: The Gulp 4 default registry.
- undertaker-common-tasks: Proof-of-concept custom registry that pre-defines tasks.