Previously, I introduced the learning to install and configure the front-end automation tool Gulp. I felt that gulp is indeed much simpler than grunt configuration, so I decided to study gulp more deeply, so I went online to check the information and found that gulp can also automatically add version numbers. This function is a problem for me to have caches on the client when updating css or js, which makes the update effect not displayed in real time. So I quickly tried it. It was really OK. I was very happy. It really provided a lot of convenience for project development and rapid display of results.
Implementation principle:
1. Modify js and css files;
2. By hashing the contents of js and css files, a unique hash string for a file is generated (if the file is modified, the hash number will change);
3. Replace the js and css file names in html and generate a file name with a version number.
Now the online solution is to generate a new dist directory, which contains the html, js, css and other files to be published. However, in actual company projects, there will be situations where new HTML cannot be generated and published. You need to replace the js and css versions on the original HTML file. Here I will share the control plan for me to change the plug-in and then perform the version under the original directory structure in the actual project. (Here, I don’t quite understand the original author’s meaning, because since you have modified js or css, the version number of these files introduced in html will inevitably change, that is, html will also change. If you do not publish the new html, then the version number in the online html is still the old version number, and it will not play the role of updating the cache. So why do we have worked hard to configure gulp to add this version number?)
Original html file code
<link rel="stylesheet" href="../css/"> <script src="../js/"></script>
Expected effect: html file code under the original directory structure
<link rel="stylesheet" href="../css/?v=5a636d79c4"> <script src="../js/?v=3a0d844594"></script> background:url("../images/?v=8f204d4")
Implementation method:
1. Install gulp and gulp plug-ins
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
2. Write
//Introduce gulp and gulp plug-insvar gulp = require('gulp'), assetRev = require('gulp-asset-rev'), runSequence = require('run-sequence'), rev = require('gulp-rev'), revCollector = require('gulp-rev-collector'); //Define the css and js source file pathvar cssSrc = 'css/*.css', jsSrc = 'js/*.js'; //Add hash encoding for pictures/fonts, etc. introduced in css ('assetRev', function(){ return (cssSrc) //The file targeted by this task .pipe(assetRev()) //The module called by this task .pipe(('src/css')); //Compiled path }); //CSS generates file hash encoding and generates file name comparison mapping ('revCss', function(){ return (cssSrc) .pipe(rev()) .pipe(()) .pipe(('rev/css')); }); //js generates file hash encoding and generates file name comparison mapping ('revJs', function(){ return (jsSrc) .pipe(rev()) .pipe(()) .pipe(('rev/js')); }); //Html replaces css and js file version ('revHtml', function () { return (['rev/**/*.json', 'View/*.html']) .pipe(revCollector()) .pipe(('View')); }); //Development and construction('default', function (done) { condition = false; runSequence( //It should be noted that the above tasks can be executed using them, but they are only executed in parallel to the maximum extent. When adding the version number, these tasks need to be executed in serial (sequence) so runSequence is used. ['assetRev'], ['revCss'], ['revJs'], ['revHtml'], done); });
The effect after executing the gulp command
//The corresponding file is generated in the rev directory{ "": "" } <link rel="stylesheet" href="../css/"> <script src="../js/"></script>
Obviously this is not the effect we need
3. Change gulp-rev and gulp-rev-collector
Open node_modules\gulp-rev\
Line 144 manifest[originalFile] = revisionedFile;
Updated to: manifest[originalFile] = originalFile + '?v=' + ;
Open nodemodules\gulp-rev\nodemodules\rev-path\
10 lines return filename + '-' + hash + ext;
Updated to: return filename + ext;
Open node_modules\gulp-rev-collector\
Line 31 if ( !_.isString(json[key]) || (json[key]).replace(new RegExp( ), '' ) !== (key) ) {
Updated to: if ( !_.isString(json[key]) || (json[key]).split('?')[0] !== (key) ) {
Open node_modules\gulp-assets-rev\
Line 78 var verStr = ( || "-") + md5;
Updated to: var verStr = ( || "") + md5;
80 lines src = (verStr, '').replace(/(\.[^\.]+)$/, verStr + "$1");
Updated to: src=src+"?v="+verStr;
Then execute the gulp command and the result is as follows (the effect is correct):
<link rel="stylesheet" href="../css/?v=803a7fe4ae"> <script src="../js/?v=3a0d844594"></script> background:url("../images/?v=8f204d4")
But if we change css and js and execute the gulp command, the result will be as follows:
<link rel="stylesheet" href="../css/?v=33379df310?v=803a7fe4ae"> <script src="../js/?v=3a0d844594?v=3a0d844594"></script>
Have you found that a version number will be added after the version number, because gulp only replaces the original file name, which does not meet the expected effect, so we thought that we also need to modify the plug-in's replacement regular expression.
4. Continue to change gulp-rev-collector
Open node_modules\gulp-rev-collector\
Line 107 regexp: new RegExp( '([\/\\\\\\\'"])' + pattern, 'g' ),
Updated to: regex: new RegExp( '([\/\\\\\\\'"])' + pattern'(\\?v=\\w{10})?', 'g' ),
Now no matter how many times you execute the gulp command, the html effect you get is
<link rel="stylesheet" href="../css/?v=5a636d79c4"> <script src="../js/?v=3a0d844594"></script>
The following is a configuration file that I wrote that can not only compile less, compress and rename css and js, but also compress html and automatically add version numbers. Of course, it also refers to the original author's method:
//Introduce gulp and gulp plug-insvar gulp = require('gulp'), less = require('gulp-less'), assetRev = require('gulp-asset-rev'), minifyCss = require('gulp-minify-css'), uglify = require('gulp-uglify'), htmlmin = require('gulp-htmlmin'), rename = require('gulp-rename'), imagemin = require('gulp-imagemin'), runSequence = require('run-sequence'), rev = require('gulp-rev'), revCollector = require('gulp-rev-collector'); //Define the css and js source file pathvar cssSrc = 'css/*.css', cssMinSrc = 'dist/css/*.css', jsSrc = 'js/*.js', jsMinSrc = 'dist/js/*.js', lessSrc = 'less/*.less', imgMinSrc = 'dist/images/*.{png,jpg,gif,ico}', htmlSrc = '*.html'; //Compile less Define a less task (custom task name) ('less', function(){ return (lessSrc) //The file targeted by this task .pipe(less()) //The module called by this task .pipe(('css'));//Compiled path }); //Add hash encoding for pictures/fonts, etc. introduced in css ('assetRev', function(){ return (cssSrc) //The file targeted by this task .pipe(assetRev()) //The module called by this task .pipe(('src')); //Compiled path }); //Compress css ('cssMin', function() { return (cssSrc) //Compressed file .pipe(rename({suffix: '.min'})) .pipe(minifyCss()) //Execute compression .pipe(('dist/css')); //Output folder }); //CSS generates file hash encoding and generates file name comparison mapping ('revCss', function(){ return (cssMinSrc) .pipe(rev()) //File name plus MD5 suffix .pipe(()) //This method must be generated .pipe(('dist/css')); //Save to the dist/css directory }); //Compress js ('uglify',function(){ return (jsSrc) .pipe(rename({suffix: '.min'})) .pipe(uglify()) .pipe(('dist/js')); }); //js generates file hash encoding and generates file name comparison mapping ('revJs', function(){ return (jsMinSrc) .pipe(rev()) .pipe(()) .pipe(('dist/js')); }); //Compress html ('htmlMin',function(){ var options = { collapseWhitespace:true, //It should be seen from the literal meaning that clearing spaces and compressing html is more important, with a relatively large effect, and the amount of compression caused by changes is also particularly large. collapseBooleanAttributes:true, //Omit the value of the Boolean attribute, such as: <input checked="checked"/>, then after setting this attribute, it will become <input checked/>. removeComments:true, //Clear the comments in the html, we should reduce the comments in the html page. removeEmptyAttributes:true, //Clear all empty properties. removeScriptTypeAttributes:true, //Clear the type="text/javascript" attribute in all script tags. removeStyleLinkTypeAttributes:true, //Clear the type attributes on all Link tags. minifyJS:true, //Compress javascript code in html. minifyCSS:true //Compress the css code in html. }; return (htmlSrc) .pipe(htmlmin(options)) .pipe(('dist/html')); }); //Html replaces css and js file version ('revHtml', function () { return (['dist/**/*.json', 'dist/html/*.html']) .pipe(revCollector()) .pipe(('dist/html')); }); //Compress image('imageMin', function () { ('images/*.{png,jpg,gif,ico}') .pipe(imagemin()) .pipe(('dist/images')); }); ('revImage', function(){ return (imgMinSrc) .pipe(rev()) .pipe(()) //This method must be .pipe(('dist/images')); }); ('default', function (done) { //condition = false; runSequence( //This method that can be executed in a maximum parallel (asynchronously) way cannot be used here. The serial method runSequence (sequence) can be used to execute these tasks in sequence after running gulp and add version numbers to the html 'less', 'assetRev', 'cssMin', 'revCss', 'uglify', 'revJs', 'imageMin', 'revImage', 'htmlMin', 'revHtml', done); });
At present, for some reason, you have to run gulp twice to add a version number to the pictures introduced in html, so you are still exploring. Please give me some advice, thank you!
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.