Gulp Installation + Use

Keywords: JSON less npm sass

Gulp-Flow-Based Automation Tool

Using gulp, you can quickly build projects and reduce IO operations
gulp executes tasks automatically in the process of project development to facilitate IO of object file content
Guidelines for the Use of Official Websites http://www.gulpjs.com.cn/docs/getting-started/

Stream flow

node.js

install

  1. Installation node, node-v detection installation success
  2. (Recommended cnmp) NPM install cnpm-g-registry= https://registry.npm.taobao.org cnmp -v shows version number
  3. Cnpm install gulp-g, gulp-v display version number
  4. New package.json in the project file root directory,
    package.json is an essential configuration file for nodejs-based projects. It is the key content of common JSON files stored in the project root directory.
  5. Enter the Project Folder
    d:
    cd cperson
  6. cnpm init, new package.json, can also be manually created
  7. The gulp plug-in is installed locally, the gulp is installed globally to perform the gulp task, and the gulp is installed locally to invoke the functions of the gulp plug-in.
  8. New gulpfile.js, gulpfile.js is the configuration file of gulp, put in the root directory
  9. Running gulp, execution considers
    Common plug-ins
    Compilation of SASS (gulp-sass)

    Less compilation (gulp-less)

    gulp-rename

    Automatic addition of css prefix (gulp-autoprefixer)

    Compressed CSS (gulp-clean-css)

    js code validation (gulp-jshint)

    Merge js files (gulp-concat)

    Compressing js code (gulp-uglify)

    Compressed pictures (gulp-imagemin)

    Automatic refresh page (gulp-live reload, Google browser, Google browser need to install live reload plug-in)

    Picture cache, gulp-cache only if the picture is replaced

    gulp-notify

gulp is task-based

var gulp = require("gulp");

gulp.task("sync", function() {
    console.log("synchronization");
});

gulp.task("async", function() {
    setTimeout(function () {
        console.log("asynchronous");
        done();
    }, 2000);
});
Run gulp sync, gulp async
D:\Cperson\front-end\gulp>gulp sync1
[18:32:50] Using gulpfile D:\Cperson\front-end\gulp\gulpfile.js
[18:32:50] Starting 'sync1'...
//synchronization
[18:32:50] Finished 'sync1' after 394 μs

D:\Cperson\front-end\gulp>gulp async
[18:35:01] Using gulpfile D:\Cperson\front-end\gulp\gulpfile.js
[18:35:01] Starting 'async'...
[18:35:01] Finished 'async' after 838 μs
//asynchronous
D:\Cperson\front-end\gulp\gulpfile.js:10
        done();
        ^
gulp.task can be dependent. The second parameter is passed into the array, which will be processed in parallel.* gulp.task("sync", ["async", "sync1", "sync2"], function() { console.log("done"); });

Processing file content

From source src to destination dest, file content and inline style, script are compressed to optimize. html

optimization

  • Page JS is stored under. / static/js, public libraries are placed under. / static/js/lib, public libraries are compressed and not merged, and page JS is compressed and merged.
  • Page CSS is stored in. / static/css, public CSS is placed in. / static/css/common, public CSS is only compressed and not merged, and page CSS is compressed and merged.
  • Pictures with less than 3kb of image resources are inlined in base64 mode and placed under. / static/img.
    Compress js
function minifyAndComboJS(name, encode, files){
  var fs = require("fs");
  var UglifyJS = require("uglify-js");
  var content = "";

  files.forEach(function(js){
    var minified = UglifyJS.minify(js).code;
    content += minified;
  });

  if(content){
    var combo = "static/js/" + name;
  }
  fs.writeFileSync(combo, content);

  gulp.src(combo)
      .pipe(gulp.dest("./dist/static/js"));
}

compress

js gulp.task("build-js-lib", function(){
  gulp.src("./static/js/lib/**/*.js")
      .pipe(through.obj(function(file, encode, cb) {
        var UglifyJS = require("uglify-js");
        var contents = file.contents.toString(encode);
        var minified = UglifyJS.minify(contents, 
          {fromString:true}).code;

        file.contents = new Buffer(minified, encode);
        cb(null, file, encode);
      }))
      .pipe(gulp.dest("./dist/static/js/lib"));
});

css

function minifyAndComboCSS(name, encode, files){
  var fs = require("fs");
  var CleanCSS = require("clean-css");
  var content = "";

  files.forEach(function(css){
    var contents = fs.readFileSync(css, encode);
    var minified = new CleanCSS().minify(contents).styles; 
    content += minified;
  });

  if(content){
    var combo = "static/css/" + name;
  }
  fs.writeFileSync(combo, content);

  gulp.src(combo)
      .pipe(gulp.dest("./dist/static/css"));
}

Compression of common css

gulp.task("build-common-css", function(){
  gulp.src("./static/css/common/**/*.css")
      .pipe(through.obj(function(file, encode, cb) {
        var CleanCSS = require("clean-css");

        var contents = file.contents.toString(encode);
        var minified = new CleanCSS().minify(contents).styles;  

        file.contents = new Buffer(minified, encode);
        cb(null, file, encode);
      }))
      .pipe(gulp.dest("./dist/static/css/common"));
});

Processing pictures

//Inline pictures
var imgs = $("img");
for(var i = 0; i < imgs.length; i++){
  var img = $(imgs[i]);
  var src = img.attr("src");
  if(/^static\/img/.test(src)){
    var stat = fs.statSync(src);
    var ext = require("path").parse(src).ext;

    if(stat.size <= 3000){
      var head = ext === ".png" ? "data:image/png;base64," : "data:image/jpeg;base64,";
      var datauri = fs.readFileSync(src).toString("base64");
      img.attr("src", head + datauri);
    }
  }
}

Compress HTML

contents = $.html();

//Compress HTML
var HTMLMinifier = require("html-minifier").minify;

var minified = HTMLMinifier(contents, {
  minifyCSS: true,
  minifyJS: true,
  collapseWhitespace: true,
  removeAttributeQuotes: true
});

Then, when dealing with index.html, we can use cheerio to parse the file and extract the external chain to be processed from the document.

Extracting js and css outer chain processing

var $ = require("cheerio").load(contents, {decodeEntities: false});

//Processing external chain css
var links = $("link");
var cssToCombo = [];

for(var i = 0; i < links.length; i++){
  var link = $(links[i]);
  if(link.attr("rel") === "stylesheet"){
    var href = link.attr("href");
    if(/^static\/css\/(?!common)/.test(href)){
      cssToCombo.push(href);
      if(cssToCombo.length == 1){
        link.attr("href", "static/css/index.min.css");
      }else{
        link.remove();
      }
    }
  }
}
minifyAndComboCSS("index.min.css", encode, cssToCombo);

// Processing External Chain js

var scripts = $("script");
var jsToCombo = [];
for(var i = 0; i < scripts.length; i++){
  var s = $(scripts[i]);

  //Judge that the script tag is indeed js
  if(s.attr("type") == null 
    || s.attr("type") === "text/javascript"){
    var src = s.attr("src");

    if(src){
      //External chain js, which by default only handles resources starting with / static /
      if(/^static\/js\/(?!lib)/.test(src)){
        jsToCombo.push(src);
        if(jsToCombo.length == 1){
          s.attr("src", "static/js/index.min.js");
        }else{
          s.remove();  
        }   
      }
    }
  }
}
minifyAndComboJS("index.min.js", encode, jsToCombo);

API

  1. gulp.src(glob[,options]) outputs files matching patterns
    gulp.src('client/templates/*.jade')
    .pipe(jade())
    .pipe(minify())
    .pipe(gulp.dest('build/minified_templates'));

    glob grammar rules

    * Match any 0 or more arbitrary characters
    Match any character
    [... ] If the characters are in middle brackets, they match. If it begins with! Or ^, if the character is not in the middle bracket, it matches.
    (pattern|pattern|pattern) Matches if all the patterns in parentheses are not satisfied
    (pattern|pattern|pattern) matches if the pattern in parentheses 0 or 1 satisfies
    + (pattern|pattern|pattern) Matches if the pattern satisfies one or more parentheses
    * (a|b|c) Patterns that satisfy 0 or more parentheses match
    @ (pattern|pat*|pat?erN) Matches when a pattern in parentheses is satisfied
    ** Cross-Path Matching of Arbitrary Characters

  2. gulp.dest(path[,options])

gulp.src('./client/templates/*.jade')
      .pipe(jade())
      .pipe(gulp.dest('./build/templates'))
      .pipe(minify())
      .pipe(gulp.dest('./build/minified_templates'));

Can be pipe in and will write files. And emits all the data, so you can pipe it to multiple folders. If a folder does not exist, it will be created automatically

  1. gulp.task(name[, deps], fn)
        gulp.task('something',function(){
        })

task will be executed with the maximum number of concurrencies, and you can add dependencies

    var gulp = require('gulp');
    // Returns a callback, so the system knows when it will complete
    gulp.task('one', function(cb) {
    // Do something -- asynchronous or otherwise
    cb(err); // If err is not null or undefined, execution stops, and note that this means execution fails
    });  
    // Defining a dependent task must be completed before the task is executed
    gulp.task('two', ['one'], function() {
    // 'one'after completion
    });

    gulp.task('default', ['one', 'two']);
  1. Monitor files and do something when they change

gulp.watch(glob[,opts], tasks)

    var watcher = gulp.watch('js/**/*.js', ['uglify','reload']);
    watcher.on('change', function(event) {
      console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
    });

gulp.watch(glob[,opts, cb])

    gulp.watch('js/**/*.js', function(event) {
      console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
    });

Posted by NCC1701 on Thu, 04 Apr 2019 20:24:31 -0700