- 压缩代码
- 生成hash值文件名
- 样式配置browserslist,智能添加css前缀
-
文件目录结构如图:
-
package.json 依赖信息
{
"name": "sign",
"version": "1.0.0",
"description": "",
"main": "index.js",
"directories": {
"lib": "lib"
},
"scripts": {
"start": "http-server -c-1",
"build": "gulp"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.12.3",
"autoprefixer": "^10.2.5",
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.7.0",
"gulp": "^4.0.2",
"gulp-autoprefixer": "^7.0.1",
"gulp-babel": "^7.0.1",
"gulp-clean": "^0.4.0",
"gulp-clean-css": "^4.3.0",
"gulp-concat": "^2.6.1",
"gulp-htmlmin": "^5.0.1",
"gulp-postcss": "^9.0.0",
"gulp-rename": "^2.0.0",
"gulp-replace": "^1.0.0",
"gulp-rev": "^9.0.0",
"gulp-rev-collector": "^1.3.3",
"gulp-uglify": "^3.0.2",
"http-server": "^0.12.3",
"postcss": "^8.2.8",
"run-sequence": "^2.2.1"
},
"browserslist": [
"last 1 version",
"> 1%",
"not ie <= 8"
]
}
- 根目录下 gulpfile.js 信息:
const gulp = require('gulp')
const babel = require('gulp-babel')
const uglify = require('gulp-uglify')
const mincss = require('gulp-clean-css')
const clean = require('gulp-clean')
const gulpHtmlMin = require('gulp-htmlmin')
const replace = require('gulp-replace')
const rev = require('gulp-rev')
const revCollector = require('gulp-rev-collector');
const autoprefixer = require('autoprefixer');
const postcss = require('gulp-postcss');
const destPath = './dest' // 输出文件位置
const srcPath = './src' // 项目文件
gulp.task('clean', function () {
// 清理文件夹
return gulp.src(destPath, { read: false, allowEmpty: true })
.pipe(clean())
})
gulp.task('minJs', function () {
//压缩js文件,且将es6语法转换为es5
return gulp.src(`${srcPath}/**/*.js`)
.pipe(babel())
.pipe(uglify())
.pipe(rev())
.pipe(gulp.dest(destPath))
.pipe(rev.manifest({
path: `${destPath}/rev-manifest.json`, // 需要配合merge使用
merge: true
}))
.pipe(gulp.dest('./'))
})
gulp.task('minCss', function () {
//合并文件
return gulp.src([`${srcPath}/**/*.css`, './index.css'])
.pipe(postcss([autoprefixer()])) // 配合package.json的 browserslist
.pipe(mincss())
.pipe(rev())
.pipe(gulp.dest(destPath))
.pipe(rev.manifest({
path: `${destPath}/rev-manifest.json`, // 需要配合merge使用
merge: true
}))
.pipe(gulp.dest('./'))
})
gulp.task('images', function () {
return gulp.src(`${srcPath}/imgs/**`)
.pipe(gulp.dest(`${destPath}/imgs`))
})
gulp.task('minHtml', function () {
return gulp.src([`${destPath}/*.json`, './index.html'])
.pipe(gulpHtmlMin({
collapseWhitespace: true, //删除空格
removeComments: true, //删除注释
}))
.pipe(replace(`${srcPath}/`, './')) // 打包后对应的目录
.pipe(revCollector()) //替换html中对应的记录
.pipe(gulp.dest(destPath))
})
gulp.task('default', gulp.series('clean', gulp.parallel('minJs', 'minCss', 'images'), 'minHtml'))
.babelrc 信息:
{
"presets": [
"env"
]
}
- 执行命令:
gulp
在dest文件中输出目录,并将ES6转为ES5