1. Introduction to Gulp

  • Gulp introduction
    • Chinese homepage: www.gulpjs.com.cn/
    • Gulp is a front-end project builder similar to Grunt, as well as an automatic task runner based on Nodejs
    • Can automatically complete the javascript/coffee/sass/less/HTML/image/CSS files such as merger, compression, inspection, monitoring file changes, the browser automatically refresh, testing and other tasks
    • Gulp is more efficient (asynchronous multitasking), easier to use, and has high quality plug-ins
  • Install nodejs and view the node-v version
  • Create a simple application called gulp_test
    | - dist | - SRC | - js | | - CSS - less | - index. HTML | - gulpfile. Js - gulp configuration file | - package. Json {" name ": "Gulp_test", "version" : "1.0.0"}Copy the code
  • Gulp installation:
    • Install gulp globally
      npm install gulp -g
      Copy the code
    • Gulp is partially installed
      npm install gulp --save-dev
      Copy the code
    • The configuration code is gulpfile.js
      Var gulp = require('gulp'); // Define the default task gulp.task(' task name ', function() {// put your task's task code here}); Gulp.task ('default', [' task '])// Execute asynchronouslyCopy the code
    • Build command:
      gulp
      Copy the code
  • Use the gulp plug-in
    • Related plug-ins:
      • Gulp-concat: Merge files (JS/CSS)
      • Gulp-uglify: compresses JS files
      • Gulp-rename: renames a file
      • Gulp-less: compiles less
      • Gulp-clean-css: compresses the CSS
      • Gulp-livereload: Real-time automatic compilation refresh
    • Important API
      • gulp.src(filePath/pathArr) :
        • Returns a file stream object that points to all files at the specified path
        • Used to read files
      • gulp.dest(dirPath/pathArr)
        • Points to all folders specified
        • Use to output files to a folder
      • gulp.task(name, [deps], fn)
        • Define a task
      • gulp.watch()
        • Monitor file changes
    • Deal with js
      • Creating a JS file
        • src/js/test1.js
          (function () { function add(num1, num2) { var num3 = 0; num1 = num2 + num3; return num1 + num2; } console.log(add(10, 30)); }) ();Copy the code
        • src/js/test2.js
          Var arr = [2,3,4]. Map (function (item, index) {return item+1; }); console.log(arr); }) ();Copy the code
      • Download plug-ins:
        npm install gulp-concat gulp-uglify gulp-rename --save-dev
        Copy the code
      • The configuration code
        var concat = require('gulp-concat'); var uglify = require('gulp-uglify'); var rename = require('gulp-rename'); gulp.task('minifyjs', Function () {return gulp.src(' SRC /js/*.js') // Pipe (concat('built ')) // Merge into temporary file.pipe (gulp.dest('dist/js')) / / generated to the target folder. Pipe (rename ({suffix: 'min'})) / / rename. Pipe (uglify ()) / / compression pipe (gulp. Dest (' dist/js')); }); gulp.task('default', ['minifyjs']);Copy the code
      • The page introduces the JS browsing test: index.html
        <script type="text/javascript" src="dist/js/built.min.js"></script>
        Copy the code
      • Package test: gulp
    • With CSS
      • Create less/ CSS files
        • src/css/test1.css
          #div1 {
            width: 100px;
            height: 100px;
            background: green;
          }
          Copy the code
        • src/css/test2.css
          #div2 {
            width: 200px;
            height: 200px;
            background: blue;
          }
          Copy the code
        • src/less/test3.less
          @base: yellow;
          .index1 { color: @base; }
          .index2 { color: green; }
          Copy the code
      • Download plug-ins:
        npm install gulp-less gulp-clean-css --save-dev 
        Copy the code
      • The configuration code
        var less = require('gulp-less'); var cleanCSS = require('gulp-clean-css'); Gulp. Task ('lessTask', function () { return gulp.src('src/less/*.less') .pipe(less()) .pipe(gulp.dest('src/css')); Gulp.task ('cssTask',['lessTask'], function () { return gulp.src('src/css/*.css') .pipe(concat('built.css')) .pipe(gulp.dest('dist/css')) .pipe(rename({suffix: '.min'})) .pipe(cleanCSS({compatibility: 'ie8'})) .pipe(gulp.dest('dist/css')); }); gulp.task('default', ['minifyjs', 'cssTask']);Copy the code
      • Page introduces CSS browsing test: index.html
        <link rel="stylesheet" href="dist/css/built.min.css">
        <div id="div1" class="index1">div1111111</div>
        <div id="div2" class="index2">div2222222</div>
        Copy the code
      • Package test: gulp
    • Handle HTML
      • Download plug-ins:
        npm install gulp-htmlmin --save-dev
        Copy the code
      • The configuration code
        var htmlmin = require('gulp-htmlmin'); Gulp.task ('htmlMinify', function() {return gulp.src('index.html'). Pipe (htmlmin({collapseWhitespace: true})) .pipe(gulp.dest('dist')); }); gulp.task('default', ['minifyjs', 'cssTask', 'htmlMinify']);Copy the code
      • Modify page import
        <link rel="stylesheet" href="css/built.min.css">
        <script type="text/javascript" src="js/built.min.js"></script>
        Copy the code
      • Package test: gulp
    • Automatic compilation
      • Download the plugin

        npm install gulp-livereload --save-dev
        Copy the code
      • Configuration code:

        var livereload = require('gulp-livereload'); // All pipe.pipe (livereload()) gulp.task('watch', ['default'], function () {// enable livereload.listen(); / / monitor the specified file, and specify the corresponding processing tasks gulp. Watch (' SRC/js / *. Js' [' minifyjs']) gulp. Watch ([' SRC/CSS / *. CSS ', 'SRC/less / *. Less']. ['cssTask','lessTask']); });Copy the code
      • Hot loading (real-time loading)

        • Download the plugin: gulp-Connect
        1, install gulp-connect --save-dev; Var connect = require('gulp-connect'); var connect = require('gulp-connect'); // All pipe.pipe (connect.reload()) // configure the loading option connect.server({root: 'dist/',// monitor the source target file path livereload: True,// whether to refresh port: 5000// enable port number}); // Automatically open the link open('http://localhost:5000'); // NPM install open --save-dev gulp.watch(' SRC /js/*.js', ['js']); // NPM install open --save-dev gulp.watch(' SRC /js/*.js', ['js']); gulp.watch(['src/css/*.css', 'src/css/*.less'], ['cssMin', 'less']);Copy the code
      • extension

        • Package and load the gulp plug-in
        • Prerequisite: Download the plug-in well.
        • Download the package: gulp-load-plugins
        • npm install gulp-load-plugins –save-dev
        • Var $= require(‘gulp-load-plugins’)(); !!!!!!!!! The imported plug-in is a method that you must remember to call.
        • Masterstroke: no more mods need to be introduced
        • Usage:
          All plugins are elicited with $, and all other plugins have the same function name (the last part of the plugin name) : for example: concat,connect, csSMin... gulp.task('less', Function () {return gulp.src(' SRC /less/*.less').pipe($.less() Pipe (gulp. Dest ('/SRC/CSS)) / / will be converted to less output files under the SRC. The pipe ($. Livereload ()) / / real-time refresh. Pipe ($. Connect. Reload ()});Copy the code

2.Gulpfile.js file configuration:

var gulp = require('glup'); // var concat = require('glup-concat'); // var uglify = require('glup-uglify'); // var rename = require('glup-rename'); // var less = require('glup-less'); // var cleanCss = require('glup-clean-css'); // var htmlmin = require('gulp-htmlmin'); // var livereload = require('gulp-livereload'); // var connect = require('gulp-connect'); // var open = require('open'); var $ = require('gulp-load-plugins')(); // Pack and load gulp plugins. Gulp.task ('js', Function () {return gulp. SRC ('/SRC/js / * * *. Js') / / depth can traverse pipe ($. Concat (' build. Js)) / / temporary consolidation file, Pipe (gulp.dest('dist/js/')) // Specify the output directory to the local directory.pipe($.uglify()) // zip the file.pipe($.rename({suffix: 'min'})) / / rename the pipe (gulp. Dest (' dist/js)) / / output/again /. Pipe (livereload ()), pipe ($. Connect. Reload ()}); Gulp. Task ('less', Function () {return gulp.src(' SRC /less/*.less').pipe($.less()).pipe(gulp.dest(' SRC/CSS ') .pipe(livereload()) .pipe($.connect.reload()) }); Gulp.task (' CSS ', ['less'], function () { return gulp.src('src/css/*.css') .pipe($.concat('built.css')) .pipe(gulp.dest('dist/css')) .pipe($.rename({suffix: '.min'})) .pipe($.cleanCss({compatibility: 'ie8'})) .pipe(gulp.dest('dist/css')) // .pipe(livereload()) .pipe($.connect.reload()) }); Gulp.task (' HTML ', function () {return gulp.src('index.html'). Pipe ($.htmlmin({collapseWhitespace: true})) .pipe(gulp.dest('dist/')) // .pipe(livereload()) .pipe($.connect.reload()) }); Gulp.task ('watch', ['default'], function () {// Enable livereload.listen(); / / monitor the specified file, and specify the corresponding processing tasks gulp. Watch (' SRC/js / *. Js' [' js]) gulp. Watch ([' SRC/CSS / *. CSS ', 'SRC/less / *. Less'], [' CSS ', 'less']); }); Glup. task('server', ['default'], function () {// Configure server options $.connect.server({root: Dist /',// monitor source target file path livereload: true,// whether real-time refresh port: 5000// enable port number}); // Automatically open the link open('http://localhost:5000'); // NPM install open --save-dev gulp.watch(' SRC /js/*.js', ['js']); // NPM install open --save-dev gulp.watch(' SRC /js/*.js', ['js']); gulp.watch(['src/css/*.css', 'src/css/*.less'], ['css', 'less']); }); / / register the default task (asynchronously) gulp. Task (' default '[' js',' less ', 'CSS', 'HTML']);Copy the code