Gulp中的任务依赖项



有如下的gulpfile.js

const { watch, src, dest, parallel, series } = require('gulp')
const uglify = require('gulp-uglify')
const browserSync = require('browser-sync').create()
const htmlMin = require('gulp-htmlmin')
const cleanCSS = require('gulp-clean-css')
const imagemin = require('gulp-imagemin')
const hash = require('gulp-hash')                   // !!!
const references = require('gulp-hash-references')  // !!!
const del = require('del')
const path = require('path')
const manifestFile = 'asset-manifest.json'
const buildDir = './build'
function serve() {
browserSync.init({
server: {
baseDir: "./"
}
})
watch("./*.html").on('change', browserSync.reload)
watch("./css/**/*.css").on('change', browserSync.reload)
watch("./**/*.js").on('change', browserSync.reload)
}
function buildHTML(cb) {
src('index.html')
.pipe(references(manifestFile)) // replace file paths in index.html according to the manifest
.pipe(htmlMin({
collapseWhitespace: true
}))
.pipe(dest(buildDir))
cb()
}
function buildCSS(cb) {
src('./css/**/*.css')
.pipe(cleanCSS())
.pipe(hash())
.pipe(dest(path.join(buildDir, 'css')))
.pipe(hash.manifest(manifestFile)) // generate a manifest file
.pipe(dest('.'))
cb()
}

function buildJS(cb) {
src(['./**/*.js', '!./node_modules/**', '!./gulpfile.js'])
.pipe(uglify())
.pipe(hash())
.pipe(dest('build/'))
.pipe(hash.manifest(manifestFile)) // generate a manifest file
.pipe(dest('.'))
cb()
}
function buildImages(cb) {
src('./img/**/*.png')
.pipe(imagemin([
imagemin.optipng({ optimizationLevel: 7 })
]))
.pipe(dest(path.join(buildDir, 'img')))
cb()
}

exports.build = series(buildJS, buildCSS, buildHTML) // !!!
exports.default = serve

我正在尝试散列*.css和*.js文件名,并在build/index.html文件中用散列的名称替换它们的旧名称。但问题是函数"buildHTML"比"资产清单"更早开始工作。创建文件。我做错了什么?

您必须对函数创建的流进行return,以确保它们按照预期的顺序运行,并捕获任何可能的错误。不需要使用回调:


function buildHTML() {
return src('index.html')
.pipe(references(manifestFile)) // replace file paths in index.html according to the manifest
.pipe(htmlMin({
collapseWhitespace: true
}))
.pipe(dest(buildDir));
}
function buildCSS() {
return src('./css/**/*.css')
.pipe(cleanCSS())
.pipe(hash())
.pipe(dest(path.join(buildDir, 'css')))
.pipe(hash.manifest(manifestFile)) // generate a manifest file
.pipe(dest('.'));
}

function buildJS() {
return src(['./**/*.js', '!./node_modules/**', '!./gulpfile.js'])
.pipe(uglify())
.pipe(hash())
.pipe(dest('build/'))
.pipe(hash.manifest(manifestFile)) // generate a manifest file
.pipe(dest('.'));
}
function buildImages() {
return src('./img/**/*.png')
.pipe(imagemin([
imagemin.optipng({ optimizationLevel: 7 })
]))
.pipe(dest(path.join(buildDir, 'img')));
}

最新更新