gulp之自动化压缩合并加版本号
这个方案主要是为了实现js/css/image的压缩合并、自动添加版本号、自动加浏览器前缀和压缩html。
先把下面这里插件 npm i (插件名) -D 安装到项目环境内
gulp-sequence //顺序执行任务
gulp-csso //css压缩
gulp-jshint //js检查
gulp-uglify'), //js压缩
gulp-imagemin //压缩图片
gulp-htmlmin //压缩html
gulp-clean //清空文件夹
gulp-rev //更改版本名 md5后缀
gulp-autoprefixer //加浏览器前缀
gulp-rev-collector //gulp-rev 的插件,用于html模板更改引用路径
目录结构
|- root
| |-dist //此目录为下面生成的
| |-css
| |-js
| |-images
| |-rev
| |-index.html
| |-node_modules
| |-src //资源目录
| |-css
| |-js
| |-images
| index.html
| gulpfile.js
| package.json
gulpfile.js文件
var gulp = require('gulp'),
gulpSequence = require('gulp-sequence'), //同步执行任务
csso = require('gulp-csso'), //css压缩
jshint = require('gulp-jshint'), //js检查
uglify = require('gulp-uglify'), //js压缩
imageMin = require('gulp-imagemin'), //压缩图片
htmlMin = require('gulp-htmlmin'), //压缩html
clean = require('gulp-clean'), //清空文件夹
rev = require('gulp-rev'), //更改版本名 md5后缀
autoFx = require('gulp-autoprefixer'), //加浏览器前缀
revCollector = require('gulp-rev-collector'); //gulp-rev 的插件,用于html模板更改引用路径
//清空文件夹
gulp.task('clean', function(){
return gulp.src('dist', {read:false})
.pipe(clean());
});
//压缩css/加浏览器前缀
gulp.task('css', function(){
return gulp.src('src/css/*.css')
.pipe(autoFx({
browsers: ['last 2 versions', 'Android >= 4.0']
}))
.pipe(csso())
.pipe(rev())
.pipe(gulp.dest('dist/css'))
.pipe(rev.manifest())
.pipe(gulp.dest('dist/rev/css'));
});
//压缩js
gulp.task('js', function(){
return gulp.src('src/js/*.js')
.pipe(uglify())
.pipe(rev())
.pipe(gulp.dest('dist/js'))
.pipe(rev.manifest())
.pipe(gulp.dest('dist/rev/js'));
});
//压缩image
gulp.task('image', function(){
return gulp.src('src/images/*.{png,jpg,gif,ico}')
.pipe(imageMin({
optimizationLevel: 5,
progressive: true,
interlaced: true,
multipass: true
}))
.pipe(rev())
.pipe(gulp.dest('dist/images'))
.pipe(rev.manifest())
.pipe(gulp.dest('dist/rev/images'));
});
//改变css引用路径
gulp.task('revCss',function(){
return gulp.src(['dist/rev/**/*.json','dist/css/*.css'])
.pipe(revCollector({
replaceReved: true
}))
.pipe(gulp.dest('dist/css'));
});
//改变html引用路径
gulp.task('rev', function(){
return gulp.src(['dist/rev/**/*.json','src/*.html'])
.pipe(revCollector({
replaceReved: true
}))
.pipe(htmlMin())
.pipe(gulp.dest('dist/'));
});
gulp.task('default', gulpSequence('clean', 'css', 'js', 'image', 'revCss', 'rev')); //按顺序执行任务
OK! 有问题,不懂的,错误,请大家积极留言!