Gulp basic concept and Application

Posted by pedrobcabral on Fri, 28 Jan 2022 07:48:54 +0100

gulp introduction, basic use

Gulp.js is an automated build tool that developers can use to automate common tasks during project development.

yarn add gulp 

Gulp cli will be installed when gulp is installed. gulpfile.js exports a function. The synchronous code mode is cancelled in the latest gulp. Every task is asynchronous. Finally, you need to call the callback function or mark the completion of the task in other ways. If there is no done in the example, an error will be reported If the task name is default, the runtime command is similar to grunt, and you can directly run yen gulp.

 exports.foo = done => {
     console.log("foo task")
     done() // Identify task completion
 }

gulp4.0 still retains the task export method of the previous version, but this method is not recommended. It is recommended to use gulp to export functions

 const gulp = require('gulp')

 gulp.task('bar', done => {
     console.log("bar task")
     done()
 })

series,parallel combined tasks

gulp can combine tasks through series and parallel. Series is executed in series and parallel is executed in parallel. For example, JS and CSS can be executed in parallel during compilation. For example, when deploying tasks, compile tasks must be executed first, and then carry out other tasks. Tasks are executed in series. The basic usage is as follows

const {
    series,
    parallel
} = require('gulp')

const task1 = done => {
    setTimeout(() => {
        console.log("task1 working")
        done()
    }, 1000);
}

const task2 = done => {
    setTimeout(() => {
        console.log("task2 working")
        done()
    }, 1000);
}

const task3 = done => {
    setTimeout(() => {
        console.log("task3 working")
        done()
    }, 1000);
}

exports.foo = series(task1, task2, task3)
exports.bar = parallel(task1, task2, task3)

serial

parallel

Asynchronous task

Common asynchronous process operation examples

// Callback mode
exports.callback = done => {
    console.log("callback task")
    done()
}

exports.callback_error = done => {
    console.log("callback task")
    done(new Error("task failed"))
}

// promise mode
exports.promise = done => {
    console.log("promise task")
    return Promise.resolve()
}

exports.promise_error = () => {
    console.log("promise task")
    return Promise.reject(new Error('task failed'))
}

// async await syntax
// Wrap a setTimeout in promise mode
const timeout = time => {
    return new Promise(resolve => {
        setTimeout(resolve, time)
    })
}
exports.async = async () => {
    await timeout(1000)
    console.log("async task")
}

const fs = require("fs")
exports.stream = () => {
    const readStream = fs.createReadStream("package.json") // Read file stream
    const writeStream = fs.createWriteStream("tmp.txt") // Write file stream
    //   pipe mode is imported into the write stream, which is similar to pouring water from one pool to another
    readStream.pipe(writeStream)
    // When the end time is readStream end, each stream has an end event
    return readStream
}

exports.stream = done => {
    const readStream = fs.createReadStream("package.json") // Read file stream
    const writeStream = fs.createWriteStream("tmp.txt") // Write file stream

    readStream.pipe(writeStream)
    // This method can also end normally, which means that only this event is registered in gulp, and the listening task ends
    readStream.on('end', () => {
        done()
    })
}

Core working principle

gulp's official definition is The streaming build system, which implements a way to build pipelines.
A workflow simulation using the underlying node file stream api: input (read stream) - > processing (transform stream) - > output (write stream)
Example to achieve css compression

const fs = require('fs')
const {
    Transform
} = require('stream')

// Simulate css file compression
exports.default = () => {
    // File read stream
    const read = fs.createReadStream('normalize.css')
    // File write stream
    const write = fs.createWriteStream('normalize.min.css')

    // File conversion stream
    const transform = new Transform({
        transform: (chunk, encoding, callback) => {
            // Implementation of core conversion process
            // Chunk = > read the contents of the stream (Buffer)
            const input = chunk.toString()
            const output = input.replace(/\s+/g, "").replace(/\/\*.+?\*\//g. ") / / replace white space characters, and then replace comments
            callback(null, output)
        }
    })
    // Import the read file stream into the write stream
    read
        .pipe(transform) // transformation
        .pipe(write) // write in
    return read
}

File operation

Gulp's file stream operation API is more powerful and easier to use than node's. The conversion stream of file processing uses independent plug-ins. Gulp creates the process of building tasks. First, the read stream is created by src, and the file processing is realized by the conversion stream of the plug-in. Finally, a write stream is created by the dest method provided by gulp and written to the target file
The above example of compressing css files is implemented with gulp api. The example is as follows
Two plug-ins need to be introduced

yarn add gulp-clean-css
yarn add gulp-rename

The code is more concise and clear

const {
    src,
    dest
} = require('gulp')
const cleanCss = require('gulp-clean-css')
const rename = require('gulp-rename')

exports.default = () => {
    // return src('src/normalize.css').pipe(dest('dist'))
    // gulp's api is more powerful and wildcards can be used
    return src('src/*.css')
        .pipe(cleanCss()) // compress
        .pipe(rename({
            extname: '.min.css'
        })) // Duplicate name order
        .pipe(dest('dist')) // pipe to dist directory
}

Topics: Front-end gulp