Gulp Introduction Guide

  • Introduction to Gulp

    • Chinese homepage: http://www.gulpjs.com.cn/
    • gulp is a front-end project-building tool similar to grunt, and also an automatic task Runner Based on Nodejs
    • Automatically complete javascript/coffee/sass/less/html/image/css and other files
      Tasks of merging, compressing, checking, monitoring file changes, browser automatic refresh, testing, etc.
    • gulp is more efficient (asynchronous multitasking), easier to use, and high quality plug-ins.

  • Install nodejs and view version: node-v

  • Create a simple application gulp_test

    |- dist
    |- src
    |- js
    |- css
    |- less
    |- index.html
    |- gulpfile.js-----gulp configuration file
    |- package.json
    {
      "name": "gulp_test",
      "version": "1.0.0"
    } 
    
  • Install gulp:

    • Global Installation gulp

      npm install gulp -g
      
    • Local installation gulp

      npm install gulp --save-dev
      
    • Configuration code: gulpfile.js

      //Introducing gulp module
      var gulp = require('gulp');
      //Define default tasks
      gulp.task('default', function() {
        // Put your default task code here
      });
    • Build commands:

      gulp
  • Using gulp plug-ins

    • Related plug-ins:
    • gulp-concat: Merge files (js/css)
    • gulp-uglify: Compressing js files
    • gulp-rename: File renaming
    • gulp-less: Compile less
    • gulp-clean-css: compressed CSS
    • Gulp-live reload: Real-time automatic compilation refresh
    • gulp-load-plugins: Load gulp plug-ins from package dependencies and attach them to selected objects.
    • open: open a file or Web address in a user's preferred application.
    • Important API
    • gulp.src(filePath/pathArr) :
      • Returns the file stream object to all files pointing to the specified path
      • Used to read files
    • gulp.dest(dirPath/pathArr)
      • Point to all specified folders
      • Used to output files to folders
    • gulp.task(name[, deps], fn)
      • Define a task
    • gulp.watch()
      • Monitor file changes
    • Processing js
    • Create js files

      • src/js/test1.js

        (function () {
          function add(num1, num2) {
            var num3 = 0;
            num1 = num2 + num3;
            return num1 + num2;
          }
          console.log(add(10, 30));
        })();
        
      • src/js/test2.js

        (function () {
          var arr = [2,3,4].map(function (item, index) {
              return item+1;
          });
          console.log(arr);
        })();
    • Download plug-ins:

      npm install gulp-concat gulp-uglify gulp-rename
      --save-dev
      
    • Configuration coding

      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') //Source files for operations
            .pipe(concat('built.js')) //Merge into temporary documents     
            .pipe(gulp.dest('dist/js')) //Generate to target folder
            .pipe(rename({suffix: '.min'})) //rename  
            .pipe(uglify())    //compress
            .pipe(gulp.dest('dist/js'));
      });
      
      gulp.task('default', ['minifyjs']);
    • Page introduction js browsing test: index.html

      <script type="text/javascript" src="dist/js/built.min.js"></script>
      
    • Packaging test: gulp
    • Processing css
    • Create less/css file

      • src/css/test1.css

        #div1 {
        
          width: 100px;
          height: 100px;
          background: green;
        
        }
      • src/css/test2.css

        #div2 {
        
          width: 200px;
          height: 200px;
          background: blue;
        }
      • src/less/test3.less

        @base: yellow;
        .index1 { color: @base; }
        .index2 { color: green; }
    • Download plug-ins:

      npm install gulp-less gulp-clean-css --save-dev 
      
    • Configuration coding

      var less = require('gulp-less');
      var cleanCSS = require('gulp-clean-css');
      
      //less Handling Tasks
      gulp.task('lessTask', function () {
      return gulp.src('src/less/*.less')
          .pipe(less())
          .pipe(gulp.dest('src/css'));
      })
      //css handles tasks, specifying dependent tasks
      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']);
    • Introducing 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>
      
    • Packaging test: gulp
    • Processing html

      • Download plug-ins:

        npm install gulp-htmlmin --save-dev
        
      • Configuration coding

        var htmlmin = require('gulp-htmlmin');
        //Compressing html tasks
        gulp.task('htmlMinify', function() {
            return gulp.src('index.html')
                .pipe(htmlmin({collapseWhitespace: true}))
                .pipe(gulp.dest('dist'));
        });
        gulp.task('default', ['minifyjs', 'cssTask', 'htmlMinify']);
        
      • Modify page introduction

        <link rel="stylesheet" href="css/built.min.css">
        <script type="text/javascript" src="js/built.min.js"></script>
      • Packaging test: gulp

    • Automatic compilation
    • Download Plug-ins

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

      var livereload = require('gulp-livereload');
      
      //All pipe s
      .pipe(livereload());
      
      gulp.task('watch', ['default'], function () {    
      //Turn on surveillance
      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']);
      });
    • Automatic page refresh

      • Download Plug-ins

        npm install open
        
      • Test access:

      • Modifying js/css/less pages automatically compiles and refreshes the browser
    gulp.task('server',['build'], function () {
    //Configure Server Options
    $.connect.server({
        root : 'dist/',//Monitored source target file path
        livereload : true,//Whether to refresh in real time
        port : 5000//Open port number
    });
    open('http://localhost:5000/');
    
    //Identify the target of the monitoring and bind the corresponding tasks
    gulp.watch('src/js/*.js', ['js']);
    gulp.watch(['src/css/*.css', 'src/less/*.less'], ['css', 'less']);
    })

gulpfile.js complete code

var gulp = require('gulp');
var $ = require('gulp-load-plugins')()
var open = require('open')
gulp.task('js',function () {
    return gulp.src('src/js/*.js')
        .pipe($.concat('build.js'))
        .pipe(gulp.dest('dist/js'))
        .pipe($.uglify('dist/js/*.js'))
        .pipe($.rename({suffix:'.min'}))
        .pipe(gulp.dest('dist/js'))
        .pipe($.connect.reload());


});
gulp.task('less',function () {
    return gulp.src('src/less/*.less')
        .pipe($.less())
        .pipe(gulp.dest('src/css'))
        .pipe($.connect.reload());
})
gulp.task('css',['less'],function () {
    return gulp.src('src/css/*.css')
        .pipe($.concat('build.css'))
        .pipe(gulp.dest('dist/css/'))
        .pipe($.rename({suffix:".min"}))
        .pipe($.cleanCss({compatibility: 'ie8'}))
        .pipe(gulp.dest('dist/css/'))
        .pipe($.connect.reload());


})
gulp.task('html',function () {
    return gulp.src('./index.html')
        .pipe($.htmlmin({collapseWhitespace: true}))
        .pipe(gulp.dest('dist/'))
        .pipe($.connect.reload());
})

gulp.task('watch',['default'],function () {
    livereload,listen();
})

gulp.task('server',['build'], function () {
    $.connect.server({
        root : 'dist/',
        livereload : true,
        port : 5000
    });
    open('http://localhost:5000/');
    gulp.watch('src/js/*.js', ['js']);
    gulp.watch(['src/css/*.css', 'src/less/*.less'], ['css', 'less']);
})


gulp.task('build', ['js','less','css','html']);
gulp.task('default',['server']);



Keywords: less npm Javascript sass

Added by Iki on Mon, 17 Jun 2019 00:01:49 +0300