Automatically adding version number by using gulp4.x to update static resource version in front end

Guide reading

Every time the project is published, there will be caching problems, resulting in page not updating, especially for wechat browser, the caching situation is more serious. Then using gulp to add version number to js and css automatically can solve the problem of cache.

There are generally two methods in online materials:

  1. Generate a new dist directory, which contains html,js,css and other files to be published.
  2. The replacement of JS and CSS versions on the original HTML file does not need to generate a new directory file.
  3. The modification scheme of the latest gulp version is as follows:

First install the following dependencies

cnpm install --save-dev gulp
cnpm install --save-dev  gulp-rev
cnpm install --save-dev gulp-rev-collector

Effect to be achieved

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>new html</title>
    <script type="text/javascript" src="js/main.js?v=f5070d029f"></script>
    <script type="text/javascript" src="js/update.js?v=5ef80a31a2"></script>
    <link rel="stylesheet" type="text/css" href="css/style1.css?v=ea327d1e60">
    <link rel="stylesheet" type="text/css" href="css/style2.css?v=cdcc595362">
</head>
<body>

		hello world ! 
    	<section class="section-box-1"></section>
		<section class="section-box-2"></section>

		<image src="./images/01.jpg?v=cbff4efc8f" />
		<image src="./images/02.jpg?v=eab799daba" />

</body>
</html>

Code logic implementation

1. Add CSS version number

let gulp = require("gulp");
let gulpLoadPlugins = require('gulp-load-plugins');
let $ = gulpLoadPlugins({lazyload: true, rename:{"gulp-ruby-sass" : "sass", "gulp-markdown-pdf": "mdpdf", "gulp-rev-collector":"revCollector", "gulp-asset-rev":"assetRev"}});

const prefix_css = (done) => {
    gulp.src("./css/*")
        .pipe($.rev()) //Add hash suffix
        .pipe(gulp.dest("./dist/css/")) //Move to dist/css
        .pipe($.rev.manifest()) //Generate file mapping
        .pipe(gulp.dest("rev/css")) //Export map file to rev/css in
    done()
}

2. Add JS version number

const prefix_js = (done) => {
    gulp.src("./js/*.js")
        .pipe($.rev())
        .pipe(gulp.dest('./dist/js/'))
        .pipe($.rev.manifest())
        .pipe(gulp.dest('rev/js'));
    done()
}

3. Add image version number

const prefix_image = (done) => {
    gulp.src("./images/*.jpg")   //Files for this task
      .pipe($.rev())  //Module called by the task
      .pipe(gulp.dest('dist/images/')) //Compiled path
      .pipe($.rev.manifest())
      .pipe(gulp.dest('rev/images'));
    done()
}

4. html compilation

const prefix_html = (done) => {
    gulp.src(["rev/**/*.json","./*.html"])
        .pipe($.revCollector())
        .pipe(gulp.dest('./'))
    done()
}

5. Final workflow

exports.default = gulp.series(prefix_css,  prefix_js, prefix_image, prefix_html)

After packing, the following problems will occur:

Problem: the suffix is put after the file name. It's not what we want

<link rel="stylesheet" href="../css/default-803a7fe4ae.css">
<script src="../js/app-3a0d844594.js"></script>

Solution: modify the source code of the imported plug-in as follows

//1. Open node_modules \ gulp Rev \ index.js and modify it as follows:

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

//2. Open nodemodules \ gulp Rev \ nodemodules \ Rev path \ index.js and modify it as follows:
 
//return modifyFilename(pth, (filename, ext) => `${filename}-${hash}${ext}`);
return modifyFilename(pth, (filename, ext) => (filename+ext) ); 

//3. Open node_modules \ gulp Rev collector \ index.js and modify it as follows:
 
var afterDelim = '[\?A-Za-z0-9_\=]*'  //Newly added
changes.push({
    regexp: new RegExp( prefixDelim + pattern + afterDelim, 'g' ), //'(\\?v=\\w{10})?'
    patternLength: pattern.length,
    replacement: '$1' + manifest[key]
});

// var cleanReplacement =  path.basename(json[key]).replace(new RegExp( opts.revSuffix ), '' );
var cleanReplacement = path.basename(json[key]).split("?")[0];

The results are as follows:

C:\web\gulp>gulp
[21:24:28] Using gulpfile C:\web\gulp\gulpfile.js
[21:24:28] Starting 'default'...
[21:24:28] Starting 'prefix_css'...
[21:24:28] Finished 'prefix_css' after 95 ms
[21:24:28] Starting 'prefix_js'...
[21:24:28] Finished 'prefix_js' after 6.72 ms
[21:24:28] Starting 'prefix_image'...
[21:24:28] Finished 'prefix_image' after 8.4 ms
[21:24:28] Starting 'prefix_html'...
[21:24:28] Finished 'prefix_html' after 51 ms
[21:24:28] Finished 'default' after 165 ms

Tags: JSON Javascript sass Ruby

Posted on Sat, 09 Nov 2019 11:46:02 -0800 by packland