Detailed front-end automation Tools gulp automatically add version number _javascript tips

Source: Internet
Author: User
Tags html page md5

Before, I introduced to learn to install and configure the front-end Automation Tool gulp, feel gulp indeed than grunt configuration is much simpler, so I decided to further study gulp, went to the Internet to check the data, found that gulp can also automatically add version number, This function is usually when I update the CSS or JS always in the client cache caused by the effect of the update can not be real-time display of distress. So hurriedly to try, really can, very happy ah, really for the project development, for the rapid display of the effect of providing a lot of convenience.

Implementation principle:

1, modify JS and CSS files;

2, through the Js,css file content hash operation, generate a file a unique hash string (if the file modification will change the hash number);

3, replace the JS,CSS file name in HTML, generate a file name with version number.

Now the online solution is to generate a new dist directory, which contains the HTML, JS, CSS and other documents to be published. However, in the actual company's project, there will be a situation can not generate new HTML to publish, need to be in the original HTML file for JS, CSS version of the replacement. Here I share the control scheme that I made in the actual project by altering the plugin and then making the version under the original directory structure. (Here, I'm a little confused by what the original author meant, since you have modified JS or CSS, then the version of HTML introduced in these files will inevitably change, that is, HTML is also followed by changes, if you do not publish new HTML, the line of the HTML version is still the old version number, There is no role in updating the cache, so we worked hard to configure Gulp to add this version number why? )

Original HTML file code

<link rel= "stylesheet" href= ". /css/default.css ">
<script src=". /js/app.js "></script>

Expected effect: HTML file code under the original directory structure

<link rel= "stylesheet" href= ". /css/default.css?v=5a636d79c4 ">
<script src=". /js/app.js?v=3a0d844594 "></script>
background:url (" ...) /images/none.png?v=8f204d4 ")

Implementation method:

1. Install Gulp and Gulp plugins

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, the preparation of gulpfile.js

Introduce Gulp and gulp plug-ins var gulp = require (' Gulp '), Assetrev = require (' Gulp-asset-rev '), runsequence = require (' Run-sequence

'), rev. = require (' Gulp-rev '), Revcollector = require (' Gulp-rev-collector ');

Definition css, JS source file path var csssrc = ' Css/*.css ', jssrc = ' js/*.js '; Add a hash code to the picture/font introduced in CSS gulp.task (' Assetrev ', function () {return gulp.src (CSSSRC)//The file targeted by this task. Pipe (Assetrev ())// The module of the call. Pipe (Gulp.dest (' src/css '));

The compiled path});
    The CSS generates the file hash code and generates Rev-manifest.json file names against the mapping Gulp.task (' Revcss ', function () {return gulp.src (CSSSRC). Pipe (rev ())
. Pipe (Rev.manifest ()). Pipe (Gulp.dest (' rev/css '));


}); JS generates a file hash code and generates Rev-manifest.json file names against the mapping Gulp.task (' Revjs ', function () {return gulp.src (JSSRC). Pipe (rev ()). P
Ipe (Rev.manifest ()). Pipe (Gulp.dest (' Rev/js '));


}); HTML replaces CSS, JS file version gulp.task (' revhtml ', function () {return gulp.src ([' Rev/**/*.json ', ' view/*.html ']). PIPE (Revcol
Lector ()). Pipe (Gulp.dest (' View '));


}); Develop and build gulp.task (' Default', function (done) {condition = false; Runsequence (///need to note that Gulp.run can also achieve all of the above tasks, but Gulp.run is the maximum of parallel execution of these tasks, while adding version numbers requires serial execution (sequential execution) of these tasks, so the use of the Runsequence
    .
[' Assetrev '], [' Revcss '], [' Revjs '], [' revhtml '], done);

 });

Effect after executing the GULP command

Rev directory generated Manifest.json corresponding file
{
 "default.css": "Default-803a7fe4ae.css"
}


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

Obviously, that's not the effect we need.

3. Change Gulp-rev and Gulp-rev-collector

Open Node_modules\gulp-rev\index.js

Line 144th Manifest[originalfile] = revisionedfile;

Update to: manifest[originalfile] = Originalfile + '? v= ' + File.revhash;

Open Nodemodules\gulp-rev\nodemodules\rev-path\index.js

10 line return filename + '-' + hash + ext;

UPDATE: return filename + ext;

Open Node_modules\gulp-rev-collector\index.js

31 Rows if (!_.isstring (json[key)) | | path.basename (Json[key]). Replace (new RegExp (Opts.revsuffix), "")!== Path.basename ( Key)) {

Update as: if (!_.isstring (json[key)) | | | path.basename (Json[key]). Split ('? ') [0]!== Path.basename (key)) {

Open Node_modules\gulp-assets-rev\index.js

78 line var verstr = (Options.verconnecter | | "-") + MD5;

Update to: var verstr = (Options.verconnecter | | "") + MD5;

80 line src = src.replace (verstr, '). Replace (/(\.[ ^\.] +) $/, Verstr + "$");

Update to: src=src+ "v=" +VERSTR;

Then execute the Gulp command, and the results are as follows (the effect is correct):

<link rel= "stylesheet" href= ". /css/default.css?v=803a7fe4ae ">
<script src=". /js/app.js?v=3a0d844594 "></script>
background:url (" ...) /images/none.png?v=8f204d4 ")

But if we change the CSS and JS, and then execute the Gulp command, the results will be as follows:

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

If you find anything, you'll add a version number after the version number, because Gulp only replaces the original filename, which doesn't work as expected, so we thought we'd also need to modify the plug-in's replacement regular expression.

4. Continue to change Gulp-rev-collector

Open Node_modules\gulp-rev-collector\index.js

Line 107th regexp:new regexp (' ([\/\\\\\ ']) ' + pattern, ' g '),

Update to: Regexp:new regexp ([\/\\\\\ ']) ' + pattern+ ' (\\?v=\\w{10})? ', ' G '

Now you don't care how many times you execute the Gulp command, the resulting HTML effect is

<link rel= "stylesheet" href= ". /css/default.css?v=5a636d79c4 ">
<script src=". /js/app.js?v=3a0d844594 "></script>

The following is my own write a can compile less, but also can compress, rename css and JS, and can compress HTML and automatically add version number of gulp.js configuration file, of course, also refer to the original author of the method:

Introduction of Gulp and Gulp plug-ins var gulp = require (' gulp '), less = require (' gulp-less '), Assetrev = require (' Gulp-asset-rev '), mini Fycss = require (' Gulp-minify-css '), uglify = require (' gulp-uglify '), Htmlmin = require (' gulp-htmlmin '), rename = req Uire (' Gulp-rename '), Imagemin = require (' Gulp-imagemin '), runsequence = require (' Run-sequence '), rev = require (' Gulp

-rev '), Revcollector = require (' Gulp-rev-collector '); Definition css, JS source file path var 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 '; The compilation less defines a less task (custom task Name) Gulp.task (' Less ', function () {return gulp.src (LESSSRC)//The file for which the task is targeted. Pipe (less ())//The task calls

module. PIPE (gulp.dest (' CSS '));//compiled path}); Add a hash code to the picture/font introduced in CSS gulp.task (' Assetrev ', function () {return gulp.src (CSSSRC)//The file targeted by this task. Pipe (Assetrev ())// The module of the call. Pipe (gulp.dest (' src '));

The compiled path}); Compress CSS Gulp.tasK (' Cssmin ', function () {return gulp.src (CSSSRC)//Compressed file. Pipe (rename ({suffix: '. Min '}). Pipe (Minifycss ())  Perform compression. Pipe (Gulp.dest (' dist/css '));

Output folder}); The CSS generates the file hash code and generates Rev-manifest.json file names against the mapping Gulp.task (' Revcss ', function () {return gulp.src (CSSMINSRC). Pipe (rev ())  The file name plus MD5 suffix. Pipe (rev.manifest ())///You must have this method to generate a Rev-manifest.json. Pipe (Gulp.dest (' dist/css '));

Save the Rev-manifest.json to the Dist/css directory}); Compressed JS gulp.task (' uglify ', function () {return gulp.src (JSSRC). Pipe (rename ({suffix: '. Min '}). Pipe (Uglify ()). P
Ipe (gulp.dest (' Dist/js '));

});
    JS generates a file hash code and generates Rev-manifest.json file names against the mapping Gulp.task (' Revjs ', function () {return gulp.src (JSMINSRC). Pipe (rev ())
. Pipe (Rev.manifest ()). Pipe (Gulp.dest (' Dist/js '));

}); Compressed HTML gulp.task (' Htmlmin ', function () {var options = {collapsewhitespace:true,//should be seen literally, clear spaces, compress HTML, this one is more heavy
    To, the role is relatively large, resulting in changes in the compression volume is particularly large. Collapsebooleanattributes:true,//omitting the value of the Boolean attribute, for example: <input checked= "cHecked "/&gt, then set this property, it will become <input checked/>.
    Removecomments:true,//clear the comments in the HTML section, 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 attribute on all link labels.
    Minifyjs:true,//Compress JavaScript code in HTML.
  Minifycss:true//Compress CSS code in HTML.
  };
Return Gulp.src (HTMLSRC). Pipe (Htmlmin (options)). Pipe (Gulp.dest (' dist/html '));

}); HTML replaces CSS, JS file version gulp.task (' revhtml ', function () {return gulp.src ([' Dist/**/*.json ', ' dist/html/*.html ']). PIPE (
Revcollector ()). Pipe (Gulp.dest (' dist/html '));

}); Compressed image gulp.task (' Imagemin ', function () {GULP.SRC (' images/*.{
Png,jpg,gif,ico} '). Pipe (Imagemin ()). Pipe (Gulp.dest (' dist/images '));

}); Gulp.task (' Revimage ', function () {return gulp.src (IMGMINSRC). Pipe (rev ()). Pipe (Rev.manifest ())//must have this method.
Pipe (Gulp.dest (' dist/images '));

}); Gulp.task (' Default ', function (DonE) {//condition = false; Runsequence (///There is no way to use the Gulp.run (asynchronous) Execution of this method, the Runsequence serial method (sequential execution) can perform these tasks in sequence after running Gulp and add the version number ' less ' to the HTML. Assetrev ', ' cssmin ', ' revcss ', ' uglify ', ' Revjs ', ' imagemin ', ' revimage ', ' htmlmin ', ' rev
Html ', done);

 });

At present, I do not know why must run two times Gulp can be introduced into the HTML of the picture added version number, so still groping, also asked the great God to give directions, thank you!

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.