Front-end Automation Tool Gulp automatically add version number tutorial

Source: Internet
Author: User
Tags comments html page json md5 regular expression require

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

Npminstall--save-dev Gulp
Npminstall--save-dev Gulp-rev
Npminstall--save-dev Gulp-rev-collector
Npminstall--save-dev Gulp-asset-rev
Npminstall--save-dev run-sequence

2, the preparation of gulpfile.js

Introduction of Gulp and Gulp Plug-ins
Vargulp = require (' Gulp '),
Assetrev = require (' Gulp-asset-rev '),
Runsequence = require (' run-sequence '),
Rev = require (' Gulp-rev '),
Revcollector = require (' Gulp-rev-collector ');
Define CSS, JS source file path
VARCSSSRC = ' Css/*.css ',
JSSRC = ' js/*.js ';
Add a hash code for Pictures/fonts introduced in CSS
Gulp.task (' Assetrev ', function () {
RETURNGULP.SRC (CSSSRC)//files for this task
. Pipe (Assetrev ())/the module called by the task
. Pipe (Gulp.dest (' src/css '))//compiled path
});
CSS generates file hash code and generates Rev-manifest.json file name against map
Gulp.task (' Revcss ', function () {
RETURNGULP.SRC (CSSSRC)
. Pipe (rev ())
. Pipe (Rev.manifest ())
. Pipe (Gulp.dest (' rev/css '));
});
JS generates file hash code and generates Rev-manifest.json file name control map
Gulp.task (' Revjs ', function () {
RETURNGULP.SRC (JSSRC)
. Pipe (rev ())
. Pipe (Rev.manifest ())
. Pipe (Gulp.dest (' Rev/js '));
});
HTML replace CSS, JS file version
Gulp.task (' revhtml ', function () {
RETURNGULP.SRC ([' Rev/**/*.json ', ' view/*.html '])
. Pipe (Revcollector ())
. Pipe (Gulp.dest (' View '));
});
Development and construction
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

The Manifest.json corresponding file is generated under the Rev directory
{
"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, and can compress, rename css and JS, while compressing 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
Vargulp = 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 CSS, JS source file path
VARCSSSRC = ' 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)
Gulp.task (' Less ', function () {
RETURNGULP.SRC (LESSSRC)//files for this task
. Pipe (less ())/the module called by the task
. Pipe (Gulp.dest (' CSS '))//compiled path
});
Add a hash code for Pictures/fonts introduced in CSS
Gulp.task (' Assetrev ', function () {
RETURNGULP.SRC (CSSSRC)//files for this task
. Pipe (Assetrev ())/the module called by the task
. Pipe (Gulp.dest (' src '));//compiled path
});
Compress CSS
Gulp.task (' Cssmin ', function () {
RETURNGULP.SRC (CSSSRC)//Compressed files
. Pipe (rename ({suffix: '. Min '})
. Pipe (Minifycss ())//Perform compression
. Pipe (Gulp.dest (' dist/css ')); Output folder
});
CSS generates file hash code and generates Rev-manifest.json file name against map
Gulp.task (' Revcss ', function () {
RETURNGULP.SRC (CSSMINSRC)
. Pipe (rev ())//filename plus MD5 suffix
. Pipe (Rev.manifest ())//You must have this method to generate a Rev-manifest.json
. Pipe (Gulp.dest (' dist/css ')); Save Rev-manifest.json to the DIST/CSS directory
});
Compress JS
Gulp.task (' uglify ', function () {
RETURNGULP.SRC (JSSRC)
. Pipe (rename ({suffix: '. Min '})
. Pipe (Uglify ())
. Pipe (Gulp.dest (' Dist/js '));
});
JS generates file hash code and generates Rev-manifest.json file name control map
Gulp.task (' Revjs ', function () {
RETURNGULP.SRC (JSMINSRC)
. Pipe (rev ())
. Pipe (Rev.manifest ())
. Pipe (Gulp.dest (' Dist/js '));
});
Compress HTML
Gulp.task (' Htmlmin ', function () {
Varoptions = {
Collapsewhitespace:true,//from the literal meaning should be able to see, clear the Space, compressed HTML, this is more important, the role is relatively large, resulting in the change in the volume of compression is particularly large.
Collapsebooleanattributes:true,//omitting the value of the Boolean attribute, for example: <input checked= "Checked"/> then, when you set this property, it becomes <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.
};
RETURNGULP.SRC (HTMLSRC)
. Pipe (Htmlmin (options))
. Pipe (Gulp.dest (' dist/html '));
});
HTML replace CSS, JS file version
Gulp.task (' revhtml ', function () {
RETURNGULP.SRC ([' Dist/**/*.json ', ' dist/html/*.html '])
. Pipe (Revcollector ())
. Pipe (Gulp.dest (' dist/html '));
});
Compress image
Gulp.task (' Imagemin ', function () {
GULP.SRC (' images/*.{ Png,jpg,gif,ico} ')
. Pipe (Imagemin ())
. Pipe (Gulp.dest (' dist/images '));
});
Gulp.task (' Revimage ', function () {
RETURNGULP.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 do this in the most parallel (asynchronous) Gulp.run method, Runsequence This serial method (sequential execution) to perform these tasks in sequence after running gulp and adding version numbers to the HTML
' Less ',
' Assetrev ',
' Cssmin ',
' Revcss ',
' Uglify ',
' Revjs ',
' Imagemin ',
' Revimage ',
' Htmlmin ',
' Revhtml ',
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!

Original link: http://www.cnblogs.com/tnnyang/p/6023475.html

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.