一、安装依赖
创建nodejs配置文件package.json
npm init -y
文件目录下就会生成package.json 文件
编辑该文件,文件内容大致入戏
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "gulpfile.js",
"dependencies": {},
"devDependencies": {
"gulp": "^3.9.1",
"gulp-clean": "^0.3.2",
"gulp-clean-css": "^3.9.0",
"gulp-jshint": "^2.0.4",
"gulp-rename": "^1.2.2",
"gulp-rev": "^7.1.2",
"gulp-rev-collector": "^1.2.2",
"gulp-uglify": "^3.0.0",
"gulp-watch": "^4.3.11",
"jshint": "^2.9.5",
"pump": "^1.0.2",
"run-sequence": "^2.2.0"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
之后执行 npm install 下载package.json中所有的dependencies
二、在根目录下创建gulp的配置文件gulpfile.js
编辑文件
//引入gulp和gulp插件
var gulp = require('gulp'),
runSequence = require('run-sequence'),
rev = require('gulp-rev'),
revCollector = require('gulp-rev-collector'),
rename = require('gulp-rename'),
uglify = require('gulp-uglify'),
clean = require('gulp-clean'),
pump = require('pump'),
watch = require('gulp-watch'),
cleanCSS = require('gulp-clean-css');;
//定义css、js源文件路径
var cssSrc = 'css/*.css',
jsSrc = ['js/*.js'];
//监控文件变化
gulp.task('watch', function () {
gulp.watch([jsSrc,cssSrc], ['default']);
});
//清空目标文件
gulp.task('cleanDst', function () {
return gulp.src(['dist','rev'], {read: false})
.pipe(clean());
});
//CSS生成文件hash编码并生成 rev-manifest.json文件名对照映射
gulp.task('revCss', function(){
return gulp.src(cssSrc)
.pipe(rev())
.pipe(rev.manifest())
.pipe(gulp.dest('rev/css'));
});
//js生成文件hash编码并生成 rev-manifest.json文件名对照映射
gulp.task('revJs', function(){
return gulp.src(jsSrc)
.pipe(rev())
//生成rev-manifest.json
.pipe(rev.manifest())
.pipe(gulp.dest('rev/js'));
});
//Html替换css、js文件版本
gulp.task('revHtml', function () {
return gulp.src(['rev/**/*.json', '*.html'])
.pipe(revCollector({
replaceReved: true
}))
.pipe(gulp.dest('dist'));
});
//开发构建
gulp.task('dev', function (done) {
condition = false;
runSequence(
['cleanDst'],
['revCss'],
['revJs'],
['revHtml'],
['watch'],
done);
});
gulp.task('default', ['dev']);
gulp 各种命令详见官方文档
三、更改gulp-rev和gulp-rev-collector
打开node_modules\gulp-rev\index.js
第144行 manifest[originalFile] = revisionedFile;
更新为::manifest[originalFile] = originalFile + '?v=' + file.revHash;
打开node_modules\rev-path\index.js
10行 return filename + '-' + hash + ext;
更新为: return filename + ext;
打开node_modules\gulp-rev-collector\index.js
40行 var cleanReplacement = path.basename(json[key]).replace(new RegExp( opts.revSuffix ), '' );
更新为:var cleanReplacement = path.basename(json[key]).split('?')[0] ;
172行 changes.push({
regexp: new RegExp( prefixDelim + pattern, 'g' ),
更新为: changes.push({
regexp: new RegExp( prefixDelim + pattern+'(\\?v=\\w{10})?', 'g' ),
四、执行gulp即可,每当有css,js文件发生改变html中的该css、js的版本号就会发生改变
附:我的新旧目录对比