码迷,mamicode.com
首页 > Web开发 > 详细

gulp之css,js压缩合并加密替换

时间:2015-11-09 15:25:33      阅读:749      评论:0      收藏:0      [点我收藏+]

标签:

为了防止客户端的静态资源缓存,我们需要每次更新css或js的时候,通过md5或时间戳等方式重新命名静态资源。让客户端可以重新请求资源,而不是从缓存里取。然后html模板里的src也要做相应的修改。当然,这里还有个附加的需要就是,静态资源需要自行优化(压缩合并)。

下面是我gulpfile.js的代码:  

var gulp = require(gulp),                        //基础库
    clean = require(gulp-clean),                 //清空文件夹
    minify = require(gulp-minify-css),           //css压缩
    rename = require(gulp-rename),               //文件重命名
    rev = require(gulp-rev),                     //更改版本名
    collector = require(gulp-rev-collector),     //gulp-rev的插件,用于html文件更改引用路径
    concat = require(gulp-concat),               //合并多个文件
    notify = require(gulp-notify);               //提示
    
gulp.task(clean,function(){              
    return gulp.src(build,{ read : false})       //src的第二个参数的{read:false},是不读取文件,加快程序。
        .pipe(clean());
})
gulp.task(index,[clean],function(){
    return gulp.src(app/index.min.html)
        .pipe(rename(function(path){
            path.basename =index;
            path.extname = ".html";
        }))
        .pipe(gulp.dest(build))
})

gulp.task(css,[index],function(cb){
    return gulp.src(app/**/*.css)
        .pipe(minify())
        .pipe(concat(main.css))
        .pipe(rename(function(path){
            path.basename +=.min;
            path.extname = ".css";
        }))
        .pipe(rev())
        .pipe(gulp.dest(build/css))
        .pipe(rev.manifest())
        .pipe(gulp.dest(build/rev));
    cb();
})

gulp.task(rev,[css],function(){
    return gulp.src([build/rev/rev-manifest.json,build/index.html])
        .pipe(collector({
            replaceReved : true
        }))
        .pipe(gulp.dest(build/))
        .pipe(notify("success!!!"))
})

 

我的目录结构:

技术分享 

 

app是原代码目录,build是gulp生成的

 

gulp之css,js压缩合并加密替换

标签:

原文地址:http://www.cnblogs.com/bq-med/p/4949250.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!