- gulp.task 移除了三參數(shù)語法,現(xiàn)在不能使用數(shù)組來指定一個(gè)任務(wù)的依賴。gulp 4.0 加入了 gulp.series 和 gulp.parallel 來實(shí)現(xiàn)任務(wù)的串行化和并行化。
任務(wù)函數(shù)中,如果任務(wù)是同步的,需要使用 done 回調(diào)。這樣做是為了讓 gulp 知道你的任務(wù)何時(shí)完成。類似這樣:
gulp.task(‘a(chǎn)’, function(done){
//sync task…
done()
})
如果任務(wù)是異步的,有多個(gè)方法可以標(biāo)記任務(wù)完成。
- 回調(diào)
gulp.task('clean', function(done) {
del(‘a(chǎn)pp/*')
.then(function() {
done()
})
.catch(function(err) {
throw err
})
})
- 返回流(Stream)
通常可以通過返回 gulp.src 實(shí)現(xiàn)。一個(gè) Stream 在完成或者發(fā)生錯(cuò)誤后會(huì)調(diào)用 end of stream 模塊,該模塊會(huì)執(zhí)行一個(gè)回調(diào)來標(biāo)記是否完成。這里說的 Stream 僅包括 readable/writable/duplex stream 等真實(shí)流,因此類似 event-stream 的偽流是不被支持的。 - 返回 Promise
把異步任務(wù)包裝成一個(gè) Promise 并返回。Promise 在完成后調(diào)用 onFulfilled 方法來標(biāo)記任務(wù)的完成。 - 返回子進(jìn)程
子進(jìn)程同樣也會(huì)在完成后調(diào)用 end of stream 模塊。
var spawn = require('child_process').spawn
gulp.task('clean', function() {
return spawn('rm', ['-rf', path.join(__dirname, 'build')])
});
事實(shí)上,所有符合 asyncDone API 的任務(wù)函數(shù),都可以用于 gulp task 中。
- gulp.dest 添加了 dirMode 參數(shù),可以指定生成文件夾的模式。
- gulp.src 的 glob 參數(shù)按順序求值,例如 gulp.src(['.js', '!b.js', 'bad.js’]),會(huì)去掉 bad.js 外所有 b 開頭的 js 文件。
- gulp.src 添加 since 選項(xiàng),只匹配在某個(gè)固定時(shí)間后有修改的文件,這可以用來做增量構(gòu)建。
gulp.task('img', function images() {
return gulp.src(Path.img.src, {since: gulp.lastRun('img')})
.pipe(plumber())
.pipe(imagemin([
imagemin.gifsicle({interlaced: true}),
imagemin.jpegtran({progressive: true}),
imagemin.optipng({optimizationLevel: 1}),
imagemin.svgo({
plugins: [
{removeViewBox: true}
]
})
]))
.pipe(gulp.dest(Path[env]))
})
- gulp.dest 添加 overwrite 選項(xiàng),用來控制是否覆蓋已存在的文件。
- gulp.task 就是一個(gè)普通函數(shù),因此在 gulp 4.0 中,我們不必把每個(gè) task 函數(shù) 都加到 gulp.task 的回調(diào)中。
gulp.task('local', gulp.series(clean, gulp.parallel(php, js), watch))
function clean() {
return spawn('rm', ['-rf', Path[env]])
}
function php() {
return gulp.src(Path.php.src, {since: gulp.lastRun(php)})
.pipe(plumber())
.pipe(gulp.dest(Path[env]))
.pipe(livereload())
}
function js() {
return gulp.src(Path.js.src, {since: gulp.lastRun(js)})
.pipe(plumber())
.pipe(gulp.dest(Path[env]))
.pipe(livereload())
}
function watch(done) {
livereload.listen()
gulp.watch('app/php/**/*.php', gulp.series(php))
gulp.watch('app/js/**/*.js', gulp.series(js))
done()
}
利用 js 函數(shù)的提升特性,我們可以在文件開頭定義 task。而在 gulp 3.0,主 task 必須在所有子 task 定義完成后才能定義。另外,這里的 clean, php 等任務(wù)實(shí)際上變成了私有的了。