gulp common set of functions (development and production separation, static resource compression optimization, code optimization, real-time compilation, hash)

Keywords: Javascript JSON sass Webpack

gulp common set of functions (development and production separation, static resource compression optimization, code optimization, real-time compilation, hash)

tags: gulp front-end automation development

[TOC]
A complete self-use framework based on self-use: cddgulp
npm point Here
github point Here
Another self-use webpack 2.x + vue2.x real-time preview front-end scaffolding based on vuepack rewriting Here

1. Functional requirements

  1. html file copy, automatic change hash file links, file content replacement

  2. css file replication and hash

  3. Replication and hash of img files

  4. Copy, compress, merge, rename, hash of js file

  5. Monitoring and automatic updating of files

  6. Other collaborations include compass/sas precompiled, browser-sync real-time preview

2. Required gulp plug-ins and details

1.package.json Extraction code: 9687

 "devDependencies": {
    "del": "^2.2.1",
    "gulp": "^3.9.1",
    "gulp-cached": "^1.1.0",
    "gulp-changed": "^1.3.1",
    "gulp-clean-css": "^2.0.12",
    "gulp-concat": "^2.6.0",
    "gulp-csscomb": "^3.0.7",
    "gulp-htmlmin": "^2.0.0",
    "gulp-imagemin": "^3.0.2",
    "gulp-replace": "^0.5.4",
    "gulp-rev": "^7.1.0",
    "gulp-rev-collector": "^1.0.5",
    "gulp-uglify": "^2.0.0"
  }

1.del
This plug-in is not a gulp plug-in, but a node plug-in or a function to delete files/folders.

2.gulp
Needless to say, the local gulp plug-in

3.gulp-cached
When this plug-in is used to copy files, it only copies files that have been changed on that line, reducing unnecessary resource operations. This speeds up the execution of gulp tasks, especially when real-time preview is required, when resources are large, such as image reproduction.

4.gulp-changed
This plug-in is similar to gulp-cacahed plug-in. It mainly copies a file. If the file has not been changed, then it is not allowed to copy to the target file. (You can't see it when you measure it, and if you use cached, you don't need to use it.)

5.gulp-clean-css
Used to de-annotate and compress css files

6.gulp-concat
Merge files, and you can add a string parameter to rename merged files

7.gulp-csscomb
Version support for css

8.gulp-htmlmin
Compressing html files, such as de-newline, de-comment, etc.

9.gulp-imagemin
Lossless compression of images in jpg, png and other formats (especially useful, but too many plug-ins in your node-modules can cause the problem of slow compression of images)

10.gulp-replace
Used to replace content in text files

11.gulp-rev
hash the file and generate the corresponding json file

12.gulp-rev-collector
Combining gulp-rev to change the reference path of hash files in html files

13.gulp-uglify
Compression of js files. Some people call it "defamation". It's really ugly.

I did not use real-time preview plug-in in gulpfile.js file, because these tasks are already a lot, gulp although fast, but also a bit slow to execute, so only external use of browser-sync real-time preview.

In addition, I use sass for css precompilation. If there is an incorrect syntax when integrating into gulp precompilation, the whole gulp monitoring task will stop completely, so I use external sass monitoring. This can be used with gulp. gulp only monitors the css file and then performs its own operations. They do their own things, and there will be no interruption if they make mistakes.

3.gulpfile.js file code details.

My Development Catalogue

source file gulpfile.js Extraction code: aea6

1. Plug-ins to be introduced

var gulp = require('gulp');
var    changed = require('gulp-changed');
var    concat = require('gulp-concat');
var    htmlmin = require('gulp-htmlmin');
var    imagemin = require('gulp-imagemin');
var    uglify = require('gulp-uglify');
var    cleanCss = require('gulp-clean-css');
var cache = require('gulp-cached');
var rev = require('gulp-rev');
var replace = require('gulp-replace');
var del = require('del');
var revCollector = require('gulp-rev-collector');

2. Detailed description of each task

1. Copy HTML task: copyHtml

The code is as follows:

//Variability of common things


var dir = '../dist';    //Variable the target root directory

gulp.task('copyHtml', function(){
    gulp.src('*.html')      //HTML files in the current directory
    .pipe(cache('copyHtml'))       //Copy only modified files
    //Pipe (changed (dir)// Only changed files can pass through
    .pipe(htmlmin({collapseWhitespace: true,
        removeComments: true
    }))     //Compression of html files, line breaking and annotation
    .pipe(replace('a.js','main.js'))        //Replace the specified text in the html file
    .pipe(gulp.dest(dir));      //Copy to the target file
});

2. Copy css task: copyCss

The code is as follows:

gulp.task('copyCss',function(){
    del([dir+'/css/**/*'],{force: true});   //  Because the old files will remain after hash every time the css file is changed, it needs to be cleared before writing each time.
    gulp.src('css/main.css')
    // .pipe(changed(dir+'/css'))
    .pipe(cleanCss({conpatibility: 'ie8'}))     //Compress
    .pipe(rev())        //Carry out hash
    .pipe(gulp.dest(dir+'/css'))        
    .pipe(rev.manifest())       //Generate the json file corresponding to hash
    .pipe(gulp.dest(dir+'/css'));
});

3. Duplicate picture task: copyImg

The code is as follows:

gulp.task('copyImg', function () {
    gulp.src('img/*')
    .pipe(cache('copyImg'))     
    // .pipe(changed(dir+'/img'))
    .pipe(imagemin())   //Compression of pictures
    .pipe(rev())
    .pipe(gulp.dest(dir+'/img'))
    .pipe(rev.manifest())
    .pipe(gulp.dest(dir+'/img'));
});

4. Copy js file task: copyJs

The code is as follows:

gulp.task('copyJs', function(){
    del([dir+'/js/**/*'],{force: true});    //Similar deletion with css
    gulp.src('js/*.js')
    .pipe(cache('copyJs'))
    .pipe(concat('main.js'))    //Merge and rename js files
    .pipe(uglify())        //Compression of merged files
    .pipe(rev())
    .pipe(gulp.dest(dir+'/js'))
    .pipe(rev.manifest())
    .pipe(gulp.dest(dir+'/js'));
});

5. File reference substitution after hash for static resources (css,js,image) in html

The code is as follows:

gulp.task('rev',function(){
      gulp.src([dir+'/**/*.json', dir+'/*.html'])     //Find json, and target html file path
     .pipe(revCollector({
         replaceReved: true,
         // dirReplacements: {
         //     'a.js':'main.js'
         // } Here is to modify the text in the file path.
     }))     //Replace
     .pipe(gulp.dest(dir));
 });
 

6. Monitor files and automate task: Watch

The code is as follows:

gulp.task('watch',function(){
    gulp.watch('*.html', ['copyHtml']);     //Monitor html files and copy them if they change
    gulp.watch('css/main.css', ['copyCss']);       //Monitor the css file and copy it if it changes
    gulp.watch('img/*.{jpg,png}',['copyImg']);      //Monitor the picture and copy it if it changes
    gulp.watch('js/*.js', ['copyJs']);      //Monitor js files and copy if changes occur
    gulp.watch(dir+'/{**/*.json,/*.html}', ['rev'])     //Monitor json files and html files, hash naming and reference changes if changes occur
});

7. Set default task: default

The code is as follows:

gulp.task('default',['copyHtml','copyCss','copyImg','copyJs','watch']
);

8. Last Works Final Task

The code is as follows:

gulp.task('cleanCache', function(){
    delete cache.caches['copyHtml','copyImg','copyJs'];
})      //Since cache does not automatically clear cached items, it needs to be eliminated manually.


gulp.task('lastWorks',['cleanCache'] );

9. Other tasks - Clear the Development Folder (dist)

The code is carefully used as follows

 gulp.task('clean', function(){
     del(['../dist/**/*'],{force: true});
 });        //Clear all files and folders in dist for use at the beginning of a new project

10. Packaging tasks for old tasks before new tasks start: package project

The code is as follows:

 gulp.task('packageProject',function(){
     var zip = require('gulp-zip'); 
     var fileName = 'projectNew_0.zip';
     gulp.src(['../dist/**/*','!../dist/{css,js,img}/*.json'])      //Find the target folder and remove the json file
     .pipe(zip(fileName))        //Compress and rename files
     .pipe(gulp.dest('../../projectNew'));       //Compress to the specified folder
 });

4. summary

Now the popular web pack management software is going to revolutionize the front-end. But gulp as an entry point can not be replaced in a short time.

5. annex

If you need gulp.file that can be previewed in real time, Click Here Extraction code: aea6

Posted by rpadilla on Mon, 08 Apr 2019 23:03:30 -0700