首页 > 技术文章 > 一个简单实用的gulpfile配置

bingcola 2017-09-15 15:50 原文

var gulp = require("gulp"),
    cssmini = require('gulp-minify-css'),   //压缩css文件
    uglify = require("gulp-uglify"),        //压缩js文件
    htmlmini = require('gulp-minify-html'), //压缩html文件
    imagemin = require('gulp-imagemin'),    //压缩图片
    rev = require("gulp-rev"),
    revCollector = require('gulp-rev-collector'),
    runSequence = require('run-sequence');


//压缩js文件
gulp.task('compress_js',function(){
    return gulp.src(['gulptest/no/js/*.js','!gulptest/no/js/*.min.js'])   //获取.js文件,同时过滤掉.min.js文件
        .pipe(uglify({preserveComments:'some'}))      // 使用uglify进行压缩,并保留部分注释
        .pipe(gulp.dest('gulptest/yes/js'))
        .pipe(rev())                     //给文件添加hash编码
        .pipe(rev.manifest())            //生成rev-mainfest.json文件作为记录
        .pipe(gulp.dest('gulptest/manifest/js'));
});

//压缩css文件
gulp.task('compress_css', function() {
    return gulp.src(['gulptest/no/css/*.css','!gulptest/no/css/*.min.css'])
        .pipe(cssmini())
        .pipe(gulp.dest('gulptest/yes/css'))
        .pipe(rev())
        .pipe(rev.manifest())
        .pipe(gulp.dest('gulptest/manifest/css'));
});

//压缩html文件
gulp.task('compress_html', function () {
    gulp.src('gulptest/no/*.html')
        .pipe(htmlmini())
        .pipe(gulp.dest('gulptest/yes'));
})

//图片压缩
gulp.task('compress_img', function () {
    gulp.src('gulptest/no/img/*.{png,jpg,gif,ico}')
        .pipe(imagemin({
            optimizationLevel: 0,  //类型:Number  默认:3  取值范围:0-7(优化等级)
            progressive: true,     //类型:Boolean 默认:false 无损压缩jpg图片
            interlaced: true,      //类型:Boolean 默认:false 隔行扫描gif进行渲染
            multipass: true        //类型:Boolean 默认:false 多次优化svg直到完全优化
        }))
        .pipe(gulp.dest('gulptest/yes/img'))
        .pipe(rev())
        .pipe(rev.manifest())
        .pipe(gulp.dest('gulptest/manifest/img'));
});



//Html替换css、js、img文件版本
gulp.task('rev_html_css', function () {
    return gulp.src(['gulptest/manifest/css/*.json', 'gulptest/no/index.html'])
        .pipe(revCollector())      //从manifest文件中收集数据并且替换html模板中的链接.
        .pipe(gulp.dest('gulptest/yes'));
});
gulp.task('rev_html_js', function () {
    return gulp.src(['gulptest/manifest/js/*.json', 'gulptest/yes/index.html'])
        .pipe(revCollector())
        .pipe(gulp.dest('gulptest/yes'));
});
gulp.task('rev_html_img', function () {
    return gulp.src(['gulptest/manifest/img/*.json', 'gulptest/yes/index.html'])
        .pipe(revCollector())
        .pipe(gulp.dest('gulptest/yes'));
});




gulp.task('build', function (done) {
    condition = false;
    runSequence(
        'compress_css',
        'rev_html_css',
        'compress_js',
        'rev_html_js',
        'compress_img',
        'rev_html_img',
        'compress_html',
    done);
});

推荐阅读