下面是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”开始工作的时间早于“asset-manifest.json”文件的创建时间。我做错了什么?
1条答案
按热度按时间ha5z0ras1#
你必须对函数创建的流进行
return
操作,以确保它们按照预期的顺序运行,并捕获任何可能的错误。无需使用回调: