为了防止客户端的静态资源缓存,我们需要每次更新css或js的时候,通过md5或时间戳等方式重新命名静态资源;
然后涉及到的html模板里的src也要做相应的修改,静态资源需要优化(压缩)
文件目录结构
html模板文件
<html> <head> <link rel="stylesheet" href="../styles/one.css"> <link rel="stylesheet" href="../styles/two.css"> </head> <body> <script type="text/javascript" src="../scripts/one.js"></script> <script type="text/javascript" src="../scripts/two.js"></script> </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‘), 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(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(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/‘)); });
task执行顺序
构建后的目录结构
构建后的html模板文件
<html> <head> <link rel="stylesheet" href="../styles/one-970d7f6a33.css"> <link rel="stylesheet" href="../styles/two-045a666e4a.css"> </head> <body> <script type="text/javascript" src="../scripts/one-d89f951793.js"></script> <script type="text/javascript" src="../scripts/two-42f73556d2.js"></script> </body> </html>
时间: 2024-10-11 03:57:51