Gulp front end automation building tool

Posted by jplavoie on Sat, 29 Jan 2022 06:52:58 +0100

What is Gulp and why

Gulp It is based on node JS is a tool to realize the automatic construction of web front-end. It can automatically and efficiently build some tasks in our work,

There are a lot of "repetitive work" in the development of Web front-end, such as compressing CSS/JS files and compiling es6 into es5, which are regular. Find these rules and write gulp configuration code to let gulp automatically perform these "repetitive work".

Common front-end construction tools include: grunt,webpack Wait

Gulp Getting Started Guide

Note: gulp3 is already a discarded version on node12. In that case, upgrade gulp4

  1. Install the latest version of gulp in the project:
npm init -y
npm install gulp-cli -g
npm install gulp -D

My display is as follows:

gulp -v
CLI version: 2.3.0
Local version: 4.0.2
  1. Create a file named gulpfile under the root directory of the project JS configuration file
// gulp3 writing method
var gulp = require('gulp'); 
gulp.task('default', function() { 
    // Put your default task code here
    console.log('Perform tasks')
   
});
// gulp4 writing method
const { src, dest } = require('gulp');

function defaulTask(cb) {
    // Put your default task code here
    console.log('Perform tasks')
    cb() //cb() is used to terminate the task
}

exports.default = defaulTask;

gulp4 creates tasks through exports.
Syntax:

exports.Task name = Function name

Perform tasks:

gulp <task> 

Task is the task name. If task is not written, it defaults to default

src(), dest(), pipe() methods in Gulp

gulp makes full use of the idea of pipeline, which is a data stream

  • src(): read in files to generate data streams, Gulp .src() path matching pattern
  • pipe(): pipe method. It can be understood as a water pipe, indicating the next operation on the data flow in memory.
  • dest(): writes the data stream to the target file.

The above three methods are in the following order:

SRC (original path) - > pipe (task 1) - > - > pipe (Task 2) - > pipe (task 3) - > pipe (task 4) - > pipe (dest))

Because gulp helps us encapsulate the stream, we can directly use the api pipe to transfer data.

gulp4 has two more functions than gulp3:

  • series(...tasks): serial execution of multiple tasks
  • parallel(...tasks): execute multiple tasks in parallel

Example 1: index. In src directory Copy the HTML file to the dist directory

// gulp3 writing method
const gulp = require('gulp')
gulp.task("copyHtml",function(){
    return gulp.src('src/index.html')
    		  .pipe( gulp.dest('dist') )
})
// gulp4 writing method
const { parallel,series,src,pipe,dest,watch } = require('gulp');
function copyHtml(){
    return src('src/index.html')
    		  .pipe( dest('dist') )
}

exports.copyHtml = copyHtml

Perform tasks in the root directory:

gulp copyHtml

gulp4 syntax: exports Task name = function name

Example 2: all suffixes in the src directory are Copy the js file to the subdirectory js in the dist directory

function copyJs(){
    return src('lib/*.js')
    		  .pipe( dest('dist/js') )
})

exports.copyJsTask = copyJs;

Pay attention to the difference between * and * *

js/*.js: matches all files with the suffix JS in the JS directory

js/**/*.js: matches all files with the suffix JS in the JS directory and the descendant directory

Api reference documents

src common matching patterns

Syntax: src(globs, [options])

  • globs: file matching pattern (similar to regular expression), which is used to match file paths (including file names)
  • options: optional parameters. Usually not

Gulp internally uses the node glob module to realize its file matching function

// Single matching mode
src('[abc].js') // Match a.js, b.js, c.js
src('[^abc].js') // Match x.js, y.js

// Exclude mode: match all js files, but exclude js files starting with b. Symbol "!" Is an exclusion operation
src(['*.js'','!b.js']) 

// Array matching mode: match all js files in js directory, all css files in css directory and all html
src(['js/*.js', 'css/*.css', '*.html']) 

// Get all files with suffix js and exclude node_modules directory
src(['**/*.js', '!node_modules/'])

Detailed explanation of Glob

watch method in Gulp

Function: monitor file changes and perform corresponding tasks

For example: listen for index. In src directory HTML file. If the file is changed, the copyHtml task will be executed automatically

const { parallel,series,src,pipe,dest,watch } = require('gulp');

function copyHtml(){
    return src('src/index.html')
    		  .pipe( dest('dist') )
}

function watchHtml(){
    watch('./src/index.html', ['copyHtml'])
}

exports.watchHtmlTask = watchHtml

Use of Gulp plug-in

We will use Gulp plug-in to accomplish the following tasks:

More gulp plug-ins reference resources

Example 1: compiling scss with gulp sass plug-in

Gulp sass plug-in needs to be installed

let {src,pipe,dest} = require('gulp')
let sass = require('gulp-sass');

function complieScss() {
	return src('./src/css/index.scss')
		.pipe(sass())
		.pipe(dest('./dist/css'))
}
exports.complieScssTask = complieScss

Example 2: compressing css with gulp cssmin plug-in

Gulp cssmin plug-in needs to be installed

var cssmin = require('gulp-cssmin');

//Compress css code
function compressCss(){
 return src('./src/style.css')
      .pipe( cssmin() )
      .pipe( dest('./dist') )
}
exports.compreCssTask = compressCss

Example 3: performing multiple operations

At the same time, the following tasks are realized:

  • Compile scss
  • Add css private prefix
  • compress
  • rename
    The gulp rename rename plug-in needs to be installed
var sass = require('gulp-sass');
var cssmin = require('gulp-cssmin');
var rename = require('gulp-rename');
const autoprefixer = require('gulp-autoprefixer'); // Add browser vendor prefix (can i use)

function  css(){
    return src('./src/scss/*.scss') // Source directory
        .pipe(sass()) // Next, compile first
        .pipe(autoprefixer({
            browsers: ['last 2 versions'],
          }))
        .pipe(cssmin()) // In compression
        .pipe(rename({
            suffix: ".min"
        }))
        .pipe(dest('./dist/css/')) // Finally, it is transported to the target directory
}

exports.cssTask = css;

browserslist target browser configuration table
Detailed explanation of parameters

Example 4: es6 to es5

With babel conversion, the installation command is:

npm install --save-dev gulp-babel @babel/core @babel/preset-env

Reference documents: https://github.com/babel/gulp-babel
Gulp Babel plug-in needs to be installed

const babel = require('gulp-babel');

gulp.task('es6', () =>
	gulp.src('src/app.js')
		.pipe(babel({
			presets: ['@babel/preset-env']
		}))
		.pipe(gulp.dest('dist'))
);

Example 5 merge transform compression js

var concat = require('gulp-concat'); // Merge js or css
var uglify = require('gulp-uglify'); // Compress js
var babel = require('gulp-babel'); // es6 to es5
function js(){
    return src('./src/js/*.js')
            .pipe(concat('all.js'))
            .pipe(babel(
                {
                    presets: ['@babel/preset-env']
                }
            ))
            .pipe( uglify())
            .pipe(dest('./dist/js/'))
}

exports.jsTask = js

Realize automatic browser refresh and (hot update)

The Browser Sync plug-in needs to be installed. The core is to synchronize the final processed stream data to the browser in the final operation

Reference code:

var browserSync = require('browser-sync'); 
function  css(){
    return src('./src/scss/*.scss') // Source directory
            .pipe(sass()) // Next, compile first
            .pipe(autoprefixer({
                browsers: ['last 2 versions'],
              }))
            .pipe(cssmin()) // In compression
            .pipe(rename({
                suffix: ".min"
            }))
            .pipe(dest('./dist/css/')) // Finally, it is transported to the target directory
            .pipe(browserSync.stream()) // Synchronize the results to the browser in real time to realize hot update
}

Start a server and listen for changes in files in real time

  • css/js changes and updates
  • html change refresh browser
// Monitor the changes of scss and js files and automatically trigger js and css tasks
function watchTask(){
    // Start a server,
    browserSync.init({
        // Specify a site root
        server:"./dist"
    })
    // And monitor the changes of files and automatically perform corresponding tasks
    watch('./src/scss/*.scss',css); // Thermal loading
    watch('./src/js/*.js',js); // Thermal loading
    watch('./src/index.html',html).on('change',browserSync.reload) // page refresh 
}

Reference documents:

gulp4 build project Automation Workflow

Objectives:

  • Implement SCSS - > CSS - > merge CSS - > compress - > rename - > dist / CSS

  • Set ES6 - > Es5 - > dist / JS

  • *. HTML compressed and copied to dist / * html

  • Start the server, automatically open the browser, monitor the changes of the above files, and realize hot loading.

  • Source code directory: src

  • Built Directory: dist

Configuration file gulpfile JS reference code:

let {src,pipe,dest,series,parallel,watch  } = require('gulp');
let del = require('del'); // Delete folders and files
let sass = require('gulp-sass'); // Compiling css
let cssmin = require('gulp-cssmin'); // compress
let rename = require('gulp-rename'); // rename
const autoprefixer = require('gulp-autoprefixer'); // Add browser vendor prefix (can i use)
var concat = require('gulp-concat'); // Merge js or css
var uglify = require('gulp-uglify'); // Compress js
var babel = require('gulp-babel'); // es6 to es5
const htmlmin = require('gulp-htmlmin'); // html compression
var browserSync = require('browser-sync'); // A server can be used to realize page hot update

function clean(){
    // Clear build directory dist
    return del(['./dist/']);
}

// Put Src / index Copy HTML to dist / index html
function html(){
    return  src('./src/index.html')
            // Compress html
            .pipe(htmlmin({ collapseWhitespace: true }))
            .pipe(dest('./dist'))
}

// Merge css or js
function js(){
    return src('./src/js/*.js')
            .pipe(concat('all.js'))
            .pipe(babel(
                {
                    presets: ['@babel/preset-env']
                }
            ))
            .pipe( uglify())
            .pipe(dest('./dist/js/'))
            .pipe(browserSync.stream()) // Synchronize the results to the browser in real time
}

//Task: compile scss into css
function  css(){
    return src('./src/scss/*.scss') // Source directory
            .pipe(sass()) // Next, compile first
            .pipe(autoprefixer({
                browsers: ['last 2 versions'],
              }))
            .pipe(cssmin()) // In compression
            .pipe(rename({
                suffix: ".min"
            }))
            .pipe(dest('./dist/css/')) // Finally, it is transported to the target directory
            .pipe(browserSync.stream()) // Synchronize the results to the browser in real time
}


// Monitor the changes of scss and js files and automatically trigger js and css tasks
function watchTask(){
    // Start a server,
    browserSync.init({
        // Specify a web site root
        server:"./dist"
    })
    // And monitor the changes of files and automatically perform corresponding tasks
    watch('./src/scss/*.scss',css); // Thermal loading
    watch('./src/js/*.js',js); // Thermal loading
    watch('./src/index.html',html).on('change',browserSync.reload) // page refresh 
}

exports.jsTask = js
exports.cleanTask= clean;
exports.watchTask= watchTask;

// The original build directory needs to be deleted before the build task
// Synchronization tasks required: 1 Delete 2 Build task
// exports.CssTask = css
// exports.build = series(clean,css);

// The development stage is generally developed under one server, which can realize the hot update gulp serve of the page 
exports.serve = parallel(html,css,js,watchTask)


// In the deployment phase, you don't need to start the server. You just need to deploy the built files to the online server to gulp build
//First delete the dist directory, and then execute the tasks js and css in parallel (js) 
exports.build = series(clean, parallel(html,js,css))



During development, start the task:

gulp serve

Build after development:

gulp build

Once configured, you can happily use gulp for project development