为了防止客户端的静态资源缓存,我们需要每次更新css或js的时候,通过md5或时间戳等方式重新命名静态资源;
然后涉及到的html模板里的src也要做相应的修改,静态资源需要优化(压缩合并)
然后涉及到的html模板里的src也要做相应的修改,静态资源需要优化(压缩合并)
文件目录结构
html模板文件
<html>
<head>
<!-- build:css styles/main.min.css -->
<link rel="stylesheet" href="../styles/one.css">
<link rel="stylesheet" href="../styles/two.css">
<!-- endbuild -->
</head>
<body>
<!-- build:js scripts/main.min.js -->
<script type="text/javascript" src="../scripts/one.js"></script>
<script type="text/javascript" src="../scripts/two.js"></script>
<!-- endbuild -->
</body>
</html>
gulp配置文件:gulpfile.js
var gulp = require('gulp'),
minifyCss = require('gulp-minify-css'),
jshint = require('gulp-jshint'),
uglify = require('gulp-uglify'),
clean = require('gulp-clean'),
rev = require('gulp-rev'),
concat = require('gulp-concat'),
revReplace = require('gulp-rev-replace'),
useref = require('gulp-useref'),
revReplace = require('gulp-rev-replace'),
revCollector = require('gulp-rev-collector');
//清空文件夹,避免资源冗余
gulp.task('clean',function(){
return gulp.src('dist',{read:false}).pipe(clean());
});
//css文件压缩,更改版本号,并通过rev.manifest将对应的版本号用json表示出来
gulp.task('css',function(){
return gulp.src('app/styles/*.css')
//.pipe( concat('wap.min.css') )
.pipe(minifyCss())
.pipe(rev())
.pipe(gulp.dest('dist/app/styles/'))
.pipe(rev.manifest())
.pipe(gulp.dest('dist/rev/css'))
});
//js文件压缩,更改版本号,并通过rev.manifest将对应的版本号用json表示出
gulp.task('js',function(){
return gulp.src('app/scripts/*.js')
//.pipe( concat('wap.min.js') )
.pipe(jshint())
.pipe(uglify())
.pipe(rev())
.pipe(gulp.dest('dist/app/scripts/'))
.pipe(rev.manifest())
.pipe(gulp.dest('dist/rev/js'))
});
//通过hash来精确定位到html模板中需要更改的部分,然后将修改成功的文件生成到指定目录
gulp.task('rev',function(){
return gulp.src(['dist/rev/**/*.json','app/pages/*.html'])
.pipe( revCollector() )
.pipe(gulp.dest('dist/app/pages/'));
});
//合并html页面内引用的静态资源文件
gulp.task('html', function () {
return gulp.src('dist/app/pages/*.html')
.pipe(useref())
.pipe(rev())
.pipe(revReplace())
.pipe(gulp.dest('dist/html/'));
})
task执行顺序
构建后的目录结构
构建后的html模板文件
<html>
<head>
<!-- build:css styles/main.min.css -->
<link rel="stylesheet" href="../styles/one-970d7f6a33.css">
<link rel="stylesheet" href="../styles/two-045a666e4a.css">
<!-- endbuild -->
</head>
<body>
<!-- build:js scripts/main.min.js -->
<script type="text/javascript" src="../scripts/one-d89f951793.js"></script>
<script type="text/javascript" src="../scripts/two-42f73556d2.js"></script>
<!-- endbuild -->
</body>
</html>
如果需要对页面内引用的资源文件进行合并,这时我们可以利用:
gulp-useref ,以及gulp-rev-replace 这两个构建工具的功能特性,然后执行gulp html 即可将index.html中引用的静态资源文件进行合并
执行gulp html之后的目录结构:
此时,构建后的html模板文件
<html>
<head>
<link rel="stylesheet" href="styles/main-8056000222.min.css">
</head>
<body>
<script src="scripts/main-d803fde67b.min.js"></script>
</body>
</html>