gulp--file compression and file fingerprints

Source: Internet
Author: User
Tags md5 browser cache

Last week it was a thing to do, is to use Gulp to the project's JS and CSS to add a version, mainly to control the release of the new version of the browser cache problem, I see a lot of tools called this approach is to add "file fingerprint", this is also applauded, where compression is a step before adding fingerprints.

First look at the file fingerprint added after the successful release of the "results."


First introduce the next Gulp file compression (compressed CSS and JS)

(the code described below moves here)

My file directory is as follows:


(The marked red part is the generated processed file)

How to use Gulp, please click here (Gulp in detail)

It's enough to put these plugins in JSON:

{
  "name": "Test",
  "version": "1.0.0",
  "description": "File compression, file fingerprint",
  "main": "Gulpfile.js",
  " Scripts ": {
    " test ":" Echo \ "Error:no test specified\" && exit 1 "
  },
  " author ":" Small Craftsman ",
  " license ": "ISC",
  "Devdependencies": {
    "gulp": "^3.9.1",
    "Gulp-concat": "^2.6.0",
    "gulp-load-plugins": "^ 1.2.4 ",
    " gulp-minify-css ":" ^1.2.4 ",
    " gulp-uglify ":" ^1.5.4 "
  }
The Gulpfile.js configuration file is as follows:

var gulp = require (' Gulp '),
    plugins = require (' Gulp-load-plugins ') ();

Gulp.task (' Minifycss ', function () {return
    gulp.src (' css/index.css ')                    //input
            . Pipe (Plugins.concat (' Style.min.css '))//      merge (the input file has multiple or merged into one)
            . Pipe (Plugins.minifycss ())                  //Compression
            . Pipe (Gulp.dest ('./'));                     Output
})
gulp.task (' Minifyjs ', function () {                        //process with CSS return
    gulp.src (' js/index.js ')
            . Pipe (Plugins.concat (' main.min.js '))
            . Pipe (Plugins.uglify ())
            . Pipe (Gulp.dest ('./'));
})
Gulp.task (' Watch ', function () {
            gulp.watch (' css/index.css ', [' minifycss ']);  "Monitor" The changes in the Index.css file, execute the compression command if a change occurs (batch monitoring files, such as./**/*.css)
            gulp.watch (' js/index.js ', [' minifyjs ']);     "Monitor" Index.js file changes, execute a compression command if a change occurs (bulk monitor files, such as./**/*.js)
})


OK, you can perform watch monitoring file changes in real time, you can also perform minifycss, Minifyjs compressed CSS, JS

CSS code before compression

/*create by cc*/
body{
    margin:0;
    padding:0;
    /*font-family: ' song body ';/
}
main{
    width:100%
. head{
    width:80%;
    height:100px;
    margin:0 Auto;
    Background:rgba (7, 95,184, 0.5)
}
. body{
    width:80%;
    height:200px;
    margin:0 Auto;
    Background:rgba (239, 228, 176, 0.6)
}
footer{
    width:80%;
    height:100px; 
    margin:0 Auto; 
    Background:green;
}

Compressed CSS Code

Body{margin:0;padding:0}.main{width:100%}.body,.footer,.head{width:80%;margin:0 auto}.head{height:100px; Background:rgba (7,95,184,.5)}.body{height:200px;background:rgba (239,228,176,.6)}.footer{height:100px; Background:green}

The configuration meaning of the Gulpfile file is clearly commented.

second , file fingerprint added.

Usually in the development of this problem will always be encountered. Their own code may have some small problems, their own at a glance to confirm the problem, but after the change is not get the results of their own, and then entangled half a day, and finally clear the browser cache, found that the cache is causing the curse. As a developer you can find out why, but if it's an ordinary user, the problem with the feedback may be that a caching problem leads to an unpleasant user experience. For this reason, it is reasonable to add a version number to the project file, and clear the page reference cache, because it is not always possible for you to require users to brush their browsers like developers every time you post updates.

Here are three ways to add a file fingerprint that you've tried:

First Type:

Additional plug-ins are required:

"Gulp-rev": "^7.1.0", "
 gulp-rev-collector": "^1.0.5"

To modify the JS name for example

Gulp.task (' Minifyjs ', function () {                        //process with CSS return
    gulp.src (' js/index.js ')
            . Pipe (' Plugins.concat (' Main.min.js '))
            . Pipe (Plugins.uglify ()).
            Pipe (Plugins.rev ())                        //To add 10-bit random hash value to main.min.js
            . Pipe ( Gulp.dest ('./'))                      //Output after modifying the name of the file
            . Pipe (Plugins.rev.manifest ())               //will generate a key value pair corresponding to the file
            . Pipe (Gulp.dest (' Rev/js ')                  //Key value pair output

})
gulp.task (' Htmlrouter ', function () {return
    gulp.src (' Rev/**/*.json ', ' Index.html ']      //
            . Pipe (Plugins.revcollector ())                //Replace the introduced file, introduce the file after modifying the name
            . Pipe (Gulp.dest ('./') )
})

Generated key value pairs:

{
  "main.min.js": "Main-336a363e91.min.js"
}

FileName to be generated after modifying the file name:

Index.html introduces changes in path:

 

After execution you can see that the revision has been made:


The second type:

Modify the file configuration of the first method to form one into form two

Form One

"Main.min.js": "Main-336a363e91.min.js"

Form Two

"Main.min.js": "Main.min.js?v=336a363e91"

The files that were replaced are:

Gulp-rev\index.js
gulp-rev\node_modules\rev-path\index.js
gulp-rev-collector\index.js

Replace file please go here

Replace each of these files,

The Gulpfile.js configuration is still the same as the result of executing the code

Generated key value pairs:

{
 "main.min.js": "Main.min.js?v=336a363e91"
}

The name of the file does not change:

Index.html introduces changes in path:

 


After execution you can see that the revision has been made:



The third type : using append

The Gulp-rev-append plug-in will pass the regular

file_decl=/(?: href=|src=|url\ () [' |]] ([^\s> "']+?) \?rev= ([^\s> "']+?) ['|"] /gi;

Find and add a version number to the specified link (the default is generated from the file MD5, so the file has not changed, and this version number will not change)

Additional plug-ins are required

"Gulp-rev-append": "^0.1.6"


The HTML reference is in the following way:

 


Note: The <script src= "main.min.js?rev=@ @hash" ></script> the file under the SRC path is required to exist, otherwise the MD5 value will not be generated, for the following reasons:

Gulpfile.js Configuration

var gulp = require (' Gulp '),
    plugins = require (' Gulp-load-plugins ') ();

Gulp.task (' Minifyjs ', function () {                        //process with CSS return
    gulp.src (' js/index.js ')
            . Pipe (' Plugins.concat (' Main.min.js '))
            . Pipe (Plugins.uglify ()).
            Pipe (Gulp.dest ('./'))                     //Need Mr. File, otherwise rev-append () invalid
           

})
gulp.task (' Htmlrouter ', function () {return
    gulp.src (' index.html ')     
            . Pipe (Plugins.revappend ())                 //Find rev=@ @hash string to generate MD5 value        
            . PIPE (Gulp.dest ('./')
})

The directory structure after execution:

The file fingerprint changed after execution:

 


After execution you can see that the revision has been made:



Summary: These methods can ensure the uniqueness of production environment files, and solve the problem of browser caching.

Something: Because these are the ways that you've tried in real projects, write blog time is not convenient to restore, so use a simple demo to do the test, but according to the actual project to do the situation will be more complex, such as the resulting file duplication, file path can not be replaced, and so on, these need to use to other gulp Plug-ins, This entry-level usage is temporarily introduced here.


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.