我希望能够重用gulp-notify成功函数。我为所有任务使用相同的格式,并希望将其清理干净。这是我现在正在做的事情的一个例子:
gulp.task('build-css', function() {
const s = gsize();
return gulp.src('src/css/main.css')
.pipe(plumber({ errorHandler: onError }))
.pipe(cssmin())
.pipe(rename({suffix: '.min'}))
.pipe(gulp.dest('dist/css'))
.pipe(s)
.pipe(notify({
title: function () {
return '<%= file.relative %> - ' + s.prettySize;
},
onLast: true,
subtitle: "Successfully Compiled",
message: "@ Time: <%= options.hour %>:<%= options.minute %>:<%= options.second %> ",
templateOptions: {
hour: new Date().getHours(),
minute: new Date().getMinutes(),
second: new Date().getSeconds()
}
}))
});
我重复使用具有多个任务的相同通知功能。我尝试过这样的事情,但每次尝试都会抛出错误。这个特殊错误与管道工 - Can't Pipe to Undefined
var onSuccess = function () {
const s = gsize();
notify({
title: function () {
return '<%= file.relative %> - ' + s.prettySize;
},
onLast: true,
subtitle: "Successfully Compiled",
message: "@ Time: <%= options.hour %>:<%= options.minute %>:<%= options.second %> ",
templateOptions: {
hour: new Date().getHours(),
minute: new Date().getMinutes(),
second: new Date().getSeconds()
}
})
};
...
gulp.task('build-css', function() {
const s = gsize();
return gulp.src('src/css/main.css')
.pipe(plumber({ errorHandler: onError }))
.pipe(autoprefixer({
browsers: ['last 6 versions'],
cascade: false
}))
.pipe(cssmin())
.pipe(rename({suffix: '.min'}))
.pipe(s)
.pipe(onSuccess())
.pipe(gulp.dest('dist/css'))
.pipe(reload({stream: true}));
});
对于如何实现这一点的任何想法都表示赞赏!
编辑在qballers解决方案之后,只有问题是我的gulp-size插件返回未定义的文件大小:
const s = gsize();
// Success Message
var notifyGeneric = {
title: function () {
return '<%= file.relative %> - ' + s.prettySize;
},
onLast: true,
subtitle: "Successfully Compiled",
message: "@ Time: <%= options.hour %>:<%= options.minute %>:<%= options.second %> ",
templateOptions: {
hour: date.getHours(),
minute: date.getMinutes(),
second: date.getSeconds()
}
};
...
gulp.task('build-css', function() {
const s = gsize();
return gulp.src(srcCssPath + 'main.css')
.pipe(plumber({ errorHandler: onError }))
.pipe(autoprefixer({
browsers: ['last 6 versions'],
cascade: false
}))
.pipe(cssmin())
.pipe(rename({suffix: '.min'}))
.pipe(s)
.pipe(notify(notifyGeneric))
.pipe(gulp.dest(cssPath))
.pipe(reload({stream: true}));
});
答案 0 :(得分:2)
不确定这是否是您正在使用的解决方案,但您可以使用对象文字来保存代码重复。
var notifyGeneric = {
title: function () {
return '<%= file.relative %> - ' + this.s.prettySize;
},
onLast: true,
subtitle: "Successfully Compiled",
message: "@ Time: <%= options.hour %>:<%= options.minute %>:<%= options.second %> ",
templateOptions: {
hour: new Date().getHours(),
minute: new Date().getMinutes(),
second: new Date().getSeconds()
},
s: {}
};
gulp.task('build-css', function() {
notifyGeneric.s = gsize();
return gulp.src('src/css/main.css')
.pipe(plumber({ errorHandler: onError }))
.pipe(cssmin())
.pipe(rename({suffix: '.min'}))
.pipe(gulp.dest('dist/css'))
.pipe(notifyGeneric.s)
.pipe(notify(notifyGeneric))
});