由于近期公司系统进场出现JS发布之后缓存问题,遂考虑使用Gulp+gulp-rev+gulp-rev-collector 给MVC中的cshtml文件中引用的js自动加上版本号进行发布
(ps:电脑需安装Node.js)
- 1 :安装 gulp相关插件
npm init npm install --save-dev gulp gulp-rev gulp-rev-collector gulp-jshint gulp-uglify gulp-rename gulp-clean run-sequence
- 2:编写gulpfile.js 文件
'use-strict';
var gulp = require('gulp'),
jshint = require('gulp-jshint'),
uglify = require('gulp-uglify'),
rename = require('gulp-rename'),
rev = require('gulp-rev'),
clean = require('gulp-clean'),
runSequence = require('run-sequence'),
combiner = require('stream-combiner2'),
revCollector = require('gulp-rev-collector');
gulp.task('clean:js', function () {
return gulp.src(['Scripts/dist'], { read: false })
.pipe(clean());
});
gulp.task('clean:cshtml', function () {
return gulp.src(['Views/dist'], { read: false })
.pipe(clean());
});
gulp.task('clean', ['clean:js', 'clean:cshtml']);
gulp.task('scripts', function () {
//var combined = combiner.obj([
// gulp.src(['Scripts/*.js', '!Scripts/_references.js', '!Scripts/*.min.js']),
// uglify(),
//gulp.dest('Scripts/dist/app/js'),
//rev({ merge: true }),
//gulp.dest('Scripts/dist/app/js'),
//rev.manifest(),
//gulp.dest('Scripts/dist/rev/js')
//]);
//combined.on('error', console.error.bind(console));
gulp.src(['Scripts/*.js', '!Scripts/_references.js', '!Scripts/*.min.js'])
.pipe(uglify())
.pipe(rename({ suffix: '.min' }))
.pipe(gulp.dest('Scripts/dist/app/js'))
.pipe(rev({ merge: true }))
.pipe(gulp.dest('Scripts/dist/app/js'))
.pipe(rev.manifest())
.pipe(gulp.dest('Scripts/dist/rev/js'));
});
gulp.task('revJs', function () {
return gulp.src(['Scripts/dist/rev/**/*.json', 'Views/**/*.cshtml', '!Views/dist/*.cshtml'])
.pipe(revCollector({
replaceReved: true
}))
.pipe(gulp.dest('Views/dist/'));
});
gulp.task('build', function (cb) {
runSequence(
['scripts']
['revJs']
, cb);
//gulp.run('revall');
});
gulp.task('default', ['build']);
- 3:执行命令
gulp clean gulp scripts gulp revJs
执行后结果如下,以后每次发布后再也不用担心js缓存问题了