Use Gulp Automation to pack and merge front-end static resources (CSS, JS file compression, add version numbers)

Source: Internet
Author: User
Tags browser cache install node

The project update iterations that are being done are more frequent, the front-end code is often packaged for deployment, and manual integration of code files is cumbersome and time-consuming, so it is decided to use Gulp instead of manually doing this work.

Front-end static resources in the release of the update will face the problem of client browser cache (refer to this article), to solve this problem can be used in two ways: The overriding method (referencing the resource with the version number, do not modify the resource file name), non-overwrite method (modify the resource file name), The main use of this article is the first version number of the way, mainly with gulp to static resources automatically add version number and compression CSS, JS.

Principle: By hashing the contents of the Js,css file, a unique hash string of a file is generated, and the hash number changes if the contents of the file are modified. The version number is appended to the file when it is referenced in HTML.

Original HTML:

1 <  href= "Css/global.css"  rel= "stylesheet"  type= "Text/css"  />2<src= "Js/fun.js"></  script>

Post-use HTML:

1 <  href= "css/global.css?v=b40a6f2a9f"  rel= "stylesheet"  type = "Text/css" /> 2 <  src= "js/fun.js?v=3a08b5fa87"></script> 

I. Environment configuration (Installation gulp)

First install node, NPM (omitted here)

Install the Gulp and the plug-ins used, and create the file gulpfile.js under the project directory.

$ NPM Install--global Gulp-    ---save---save-dev gulp---save-dev gulp-rev--- Save-dev run---save-dev gulp---save-dev gulp-minify---save-dev gulp-uglify

Create a file under the project directory Gulpfile.js

Project directory Structure:

Node_modules is installed in the gulp and a variety of plug-ins

Ii. Preparation of Gulpfile.js

1 //Introducing Gulp and Gulp plugins2 varGulp = require (' Gulp ')),3Runsequence = require (' run-sequence ')),4Rev = require (' Gulp-rev '),5Clean = require (' Gulp-clean '),6Minifycss=require (' Gulp-minify-css '),7Uglify=require (' gulp-uglify '),8Revcollector = require (' Gulp-rev-collector '));9 Ten //define CSS, JS source file path One varCSSSRC = './**/*.css ',//Select all CSS in the directory AJSSRC = './**/*.js ',//Select all CSS in the directory -Srcexclude = '!. /node_modules/**/* ',//exclude files in the Node_modules -Cssfile = ' css/**/* ',//CSS Folders theImageFile = ' image/**/* ',//Picture Folder -Jsfile = ' js/**/* ',//js folder -Jscompresspath = ' Publish/js/*.js ',//JS in the compression publish -Csscompresspath = ' publish/css/*.css ';//compressing the CSS in publish +  -  + //CSS generate file hash code and generate Rev-manifest.json file name control map AGulp.task (' Revcss ',function(){ at     returnGULP.SRC ([Csssrc, Srcexclude]) - . Pipe (rev ()) - . Pipe (Rev.manifest ()) -. Pipe (Gulp.dest (' Rev/css ')); - }); -  in //js generate file hash code and generate Rev-manifest.json file name control map -Gulp.task (' Revjs ',function(){ to     returnGULP.SRC ([Jssrc, Srcexclude]) + . Pipe (rev ()) - . Pipe (Rev.manifest ()) the. Pipe (Gulp.dest (' Rev/js ')); * }); $ Panax Notoginseng  - //HTML replacement CSS, JS file version theGulp.task (' revhtml ',function () { +     returnGULP.SRC ([' Rev/**/*.json ', ' *.html ']) A . Pipe (Revcollector ()) the. Pipe (Gulp.dest (' Publish ')); + }); -  $ //copy files other than HTML $Gulp.task (' Copy ',function(){ -     returnGULP.SRC ([Cssfile, Jsfile, imagefile],{Base: '. ')}) -. Pipe (Gulp.dest (' Publish ')); the }); - Wuyi //Compression JS theGulp.task (' jscompress ',function(){ -     returngulp.src (Jscompresspath) Wu . Pipe (Uglify ()) -. Pipe (Gulp.dest ("Publish/js")); About }); $  - //Compress CSS -Gulp.task (' csscompress ',function(){ -     returngulp.src (Csscompresspath) A . Pipe (Minifycss ()) +. Pipe (Gulp.dest ("Publish/css")); the }); -  $ //Development and Construction theGulp.task (' Dev ',function(done) { theCondition =false; the Runsequence ( the[' Clean '], -[' Revcss '], in[' Revjs '], the[' revhtml '], the[' Copy '], About[' Jscompress '], the[' Csscompress '], the Done ); the }); +  -Gulp.task (' Clean ',function(){ theGULP.SRC (' rev ', {read:false}). Pipe (Clean ());Bayi     returnGULP.SRC (' Publish ', {read:false}). Pipe (Clean ()); the }); the  -  -Gulp.task (' Default ', [' Dev ']);

Third, change the plug-in code

Execute the GULP command directly under the project directory

$ gulp

will get the following effect:

1 <  href= "Css/global-b40a6f2a9f.css"  rel= "stylesheet"  type  = "Text/css"/>2<src= "Js/fun-3a08b5fa87.js"  ></script>

You need to change the code for the Gulp-rev, Rev-path, Gulpl-rev-collector plugins:

1.node_modules/gulp-rev/index.js

Line 135th: manifest[originalfile] = revisionedfile;

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

2.node_modules/rev-path/index.js

Line 9th: Return Modifyfilename (PTH, (filename, ext) = ' ${filename}-${hash}${ext} ');

Changed to: Return Modifyfilename (PTH, (filename, ext) = ' ${filename}${ext} ');

3.node_modules/gulp-rev-collector/index.js

Line 40th: var cleanreplacement = Path.basename (Json[key]). Replace (new RegExp (Opts.revsuffix), ");

Change to: var cleanreplacement = Path.basename (Json[key]). Split ('? ') [0];

It is important to note that the plugin version is not the same, the need to change the place will be different;

Here are the versions of all plugins in this article:

[Email protected] 3.9. 1 [email protected][email protected][email protected] Run [Email protected] 2.2. 1 Gulp [Email protected] 0.4. 0 Gulp [Email protected] 1.2. 4 Gulp [Email protected] 3.0. 0

The effect after the change is finished

1 <  href= "css/global.css?v=b40a6f2a9f"  rel= "stylesheet"  type = "Text/css" /> 2 <  src= "js/fun.js?v=3a08b5fa87"></script> 

Iv. Summary

The execution of the Gulp task is asynchronous and you want to ensure the order in which the tasks are executed, using the Run-sequence plugin

1Gulp.task (' Dev ',function(done) {2Condition =false;3 Runsequence (4[' Clean '],5[' Revcss '],6[' Revjs '],7[' revhtml '],8[' Copy '],9[' Jscompress '],Ten[' Csscompress '], One Done ); A});

Here the tasks are performed in order:

First clear the Old Rev and Pulish folders and all the files (clean), then generate the CSS filename against the mapped JSON file (REVCSS), then generate the JS file name against the mapped JSON (REVJS), and then replace the HTML link, Add the version number (revhtml), copy the other static resources in addition to HTML to publish (copy), then compress the JS file in the Publish/js, and replace the compressed file with the original uncompressed file (jscompress), Finally, compress the CSS files in the PUBLISH/CSS and replace the uncompressed files (csscompress).

Ps:

1. When writing a path, "!" is an excluded identity that can exclude some files, such as:

GULP.SRC (['./**/*.css ', '!. /node_modules/**/* '])

The file selected here is the CSS file in addition to the other folders in Node_modules

2. To maintain the path when copying, you need to add a base option, namely:

GULP.SRC (' Publish/css/*.css ', {base: '. '})

You can then write tasks separately for the test environment and production environment, using commands to package separately.

Use Gulp Automation to pack and merge front-end static resources (CSS, JS file compression, add version numbers)

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.