Increment the version number of an existing static file using gulp

Nonsense: a lot of later projects need to add a version number to the project and clear the browser cache, so use this ghost to do
it. Of course, you need to use the npm tool of nodeJS to install some things
. If you don't know nodejs, you must Baidu first!

Preparation: You need to install these plugins with npm package.

npm install --save-dev gulp
npm install --save-dev gulp-rev
npm install --save-dev gulp-rev-collector
npm install --save-dev gulp-asset-rev
npm install --save-dev run-sequence

Of course, my first installation failed and I couldn't start gulp;

So, I used the global install gulp command as:

npm -g install gulp

I use win7, so I ran it in CMD and found that the installation was successful

Ok, let's start adding the version number to our project

Step 1: Open node_modules\gulp-rev\index.js

Find the following code, change the commented out to the following content, here is the format of the version number returned

/*manifest[originalFile] = revisionedFile;*/
manifest[originalFile] = originalFile + '?v=' + file.revHash;

Step 2: Open node_modules\rev-path\index.js 

Find the following code, change the commented out to the following content, here is to change the associated underline (Laozi couldn't find this after searching for a long time rev-path, because the previous gulp-revplug-in integrated this part in it, and the subsequent version It rev-pathwill be gulp-revextracted from it, so to node_modulesfind this plugin in the project directory, we don't need to install it manually, this is gulp-reva dependency, and npm will install it automatically!)

/*return filename + '-' + hash + ext;*/
return filename + ext;

Step 3: Open node_modules\gulp-rev-collector\index.js

Find the following code, change the commented out to the following content, it is best to change this file in three places

one place:

/*if ( !_.isString(json[key]) || path.basename(json[key]).replace(new RegExp( opts.revSuffix ), '' ) !==  path.basename(key) ) {
          isRev = 0;
  }*/

  if ( !_.isString(json[key]) || path.basename(json[key]).split('?')[0] !== path.basename(key) ) {
          isRev = 0;
  }

Second place:

 //return pattern.replace(/[\-\[\]\{\}\(\)\*\+\?\.\^\$\|\/\\]/g, "\\$&");
	//禁止重复添加版本号
    var rp = pattern.replace(/[\-\[\]\{\}\(\)\*\+\?\.\^\$\|\/\\]/g, "\\$&");
    rp = pattern + "(\\?v=(\\d|[a-z]){8,10})*";
    return rp;

Three places:

/*patterns.push( escPathPattern( (path.dirname(key) === '.' ? '' : closeDirBySep(path.dirname(key)) ) + path.basename(key, path.extname(key)) )
                            + opts.revSuffix
                            + escPathPattern( path.extname(key) )
                        );*/

 patterns.push( escPathPattern( (path.dirname(key) === '.' ? '' : closeDirBySep(path.dirname(key)) ) + path.basename(key, path.extname(key)) )
                            + opts.revSuffix
                            + escPathPattern( path.extname(key) ) + "(\\?v=(\\d|[a-z]){8,10})*"
                        );

If you have done too much of the above, you can create a file. Of course, it is best to create this directory in the first-level directory under the project name.

For example my directory is:

Step 4: Create a gulpfile.js file in the following directory.

The content is:

//引入gulp和gulp插件
var gulp = require('gulp'),
  assetRev = require('gulp-asset-rev'),
  runSequence = require('run-sequence'),
  rev = require('gulp-rev'),
  revCollector = require('gulp-rev-collector');
//定义css、js源文件路径并且可以传入多个不同的文件夹
var cssSrc = 'css/*.css',
  jsSrc = 'js/lib/config.js',
  jsGA = 'js/lib/GA.js',
  baseTrend = 'js/lib/pk10BaseTrend.js',
  jsSrcc = 'js/loacal/**/*.js',
  ico = 'img/icon/*.ico';
//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([jsSrcc,jsSrc,jsGA,baseTrend])
    .pipe(rev())
    .pipe(rev.manifest())
    .pipe(gulp.dest('rev/js'));
});
//js生成文件hash编码并生成 rev-manifest.json文件名对照映射
gulp.task('revIco', function(){
  return gulp.src(ico)
    .pipe(rev())
    .pipe(rev.manifest())
    .pipe(gulp.dest('rev/ico'));
});
//Html替换css、js文件版本
gulp.task('revHtml', function () {
  return gulp.src(['index.html','*/**/*.*'])//将所有文件打包到新文件下
    .pipe(revCollector())
    .pipe(gulp.dest('KJW_HTML'));
});
//为css中引入的图片/字体等添加hash编码
gulp.task('assetRev', function(){
  return gulp.src(cssSrc)  //该任务针对的文件
   .pipe(assetRev()) //该任务调用的模块
   .pipe(gulp.dest('KJW_HTML/css')); //编译后的路径
});
//以下是拷贝静态图片和声音
gulp.task('copyimg',  function() {
  return gulp.src(['img/**/*'])
    .pipe(gulp.dest('KJW_HTML/img'))
});
gulp.task('copyLibimg',  function() {
  return gulp.src(['js/lib/finishAnimation/*/*.*'])
    .pipe(gulp.dest('KJW_HTML/js/lib/finishAnimation'))
});
gulp.task('copyMedia',  function() {
  return gulp.src(['media/*'])
    .pipe(gulp.dest('KJW_HTML/media'))
});
//开发构建
gulp.task('default', function (done) {
  condition = false;
  runSequence(    //说明,用gulp.run也可以实现以上所有任务,只是gulp.run是最大限度的并行执行这些任务,而在添加版本号时需要串行执行(顺序执行)这些任务,故使用了runSequence.
    ['revCss'],
    ['revJs'],
    ['revIco'],
    ['revHtml'],
    ['assetRev'],
    ['copyimg'],
    ['copyLibimg'],
    ['copyMedia'],
    done);
});

ok, just run it directly at the end

D:\DFF\PROJECT\KJW_HTML>gulp
[19:41:14] Using gulpfile D:\DFF\PROJECT\KJW_HTML\gulpfile.js
[19:41:14] Starting 'default'...
[19:41:14] Starting 'assetRev'...
[19:41:14] Finished 'assetRev' after 123 ms
[19:41:14] Starting 'revCss'...
[19:41:14] Finished 'revCss' after 25 ms
[19:41:14] Starting 'revJs'...
[19:41:14] Finished 'revJs' after 75 ms
[19:41:14] Starting 'revIco'...
[19:41:14] Finished 'revIco' after 3.06 ms
[19:41:14] Starting 'revHtml'...
[19:41:16] Finished 'revHtml' after 1.34 s
[19:41:16] Finished 'default' after 1.58 s

D:\DFF\PROJECT\KJW_HTML>

After you run it, you can see that all static files have version numbers behind them, because some resource directories that do not need to be changed do not need to be changed, such as jq and other functional plug-ins

After adding:

 

Abstract: For more front-end learning, please join the group: JS/NDEJS/HTML5/ (front-end) 458633781 or pay attention to the public account of Xinmei Body: ilittlekiss

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325440253&siteId=291194637