directory
- Glup
- How to use Gulp
- Basic use of Gulp
- The installation
- start
- The default task
- Task registration prior to gulp4.0
- Gulp composite tasks
- Gulp asynchronous task
- Call back to solve
- stream
- Core working principle of Gulp construction process
- Gulp read stream and write stream API
I have written a version of gulp before 4.0. Here I refer to gulp (old version before 4.0), an automated process building tool, but don’t read it.
Glup
Characteristic is efficient, easy to use. Developing with Gulp is simple.
How to use Gulp
- Install one in your project
Gulp
Development dependency of - Add one in the root directory
gulpfile.js
File, used to write something neededGulp
Some tasks built automatically - Pass through the command line
cli
To run these tasks
Basic use of Gulp
The installation
npm i gulp
Copy the code
start
- To create a
gulpfile.js
This is a filegulp
Entry file of - Create a task in a file
PS: In the latest version of gulp, the synchronous code mode has been removed. The convention is that each task is an asynchronous task and the task is marked as complete when it is completed. Otherwise, an error will be reported
// gulpfile.js
exports.foo = () = > {
console.log("foo task working~")}// Do you forget to add the end?
// Starting 'foo'...
// foo task working~
// The following tasks did not complete: foo
// Did you forget to signal async completion?
Copy the code
If done is added, the task is complete
// gulpfile.js
exports.foo = done= > {
console.log("foo task working~")
done() // Indicate that the task is complete
}
Copy the code
- Command line operation
gulp foo
# Using gulpfile E:\professer\Gulp\gulpfile.js
# Starting 'foo'...
# foo task working~
# Finished 'foo' after 2.43ms
Copy the code
The default task
exports.default = done= > {
console.log("default task working~")
done()
}
Copy the code
No task needs to be specified at runtime
gulp
# Using gulpfile E:\professer\Gulp\gulpfile.js
# Starting 'default'...
# default task working~
# Finished 'default' after 3.03 ms
Copy the code
Task registration prior to gulp4.0
Prior to Gulp 4.0, the registration task needed to be implemented in a method of the GULP module
const gulp = require("gulp")
gulp.task('bar'.done= > {
console.log('bar working~')
done()
})
Copy the code
This is no longer recommended, although it can be used after 4.0. It is recommended that you define gulp tasks by exporting function members.
Gulp composite tasks
The Series and Parallel apis in the GULP module make it easy to create composite tasks to execute serial and parallel tasks separately.
// Introduce the serial parallel method
const {series, parallel} = require("gulp")
// Combine tasks
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)}// Serial task structure
// Accept any number of arguments, each of which is a task to be executed in sequence
exports.hello1 = series(task1, task2, task3)
// Parallel task structure
exports.hello2 = parallel(task1, task2, task3)
Copy the code
Command line operation
gulp hello1
Task2 is executed after task1, task3 is executed after task2
# Using gulpfile E:\professer\Gulp\gulpfile.js
# Starting 'task1'...
# task1 working!
# Finished 'task1' after 1.01s
# Starting 'task2'...
# task2 working!
# Finished 'task2' after 1 s
# Starting 'task3'...
# task3 working!
# Finished 'task3' after 1.01s
# Finished 'hello1' after 3.08s
gulp hello2
Task1, task2, task3 are executed simultaneously
# Using gulpfile E:\professer\Gulp\gulpfile.js
# Starting 'hello2'...
# Starting 'task1'...
# Starting 'task2'...
# Starting 'task3'...
# task1 working!
# Finished 'task1' after 1.01s
# task2 working!
# Finished 'task2' after 1.02 s
# task3 working!
# Finished 'task3' after 1.02 s
# Finished 'hello2' after 1.02 s
Copy the code
use
- For example, if a deployment project needs to perform a compile task first, it needs a serial task.
- For example,
css
andjs
Compilation and compression, independent of each other, can use parallel tasks.
Gulp asynchronous task
Call back to solve
1. Plain callback
exports.callback = done= > {
console.log("callback task~")
done()
}
Copy the code
If we want to return an error callback, we need to pass arguments in done
exports.callback_error = done= > {
console.log("callback error task~")
done(new Error('task failed~'))}Copy the code
Running observations at this point will report an error, and subsequent tasks will not continue.
gulp callback_error
# Using gulpfile E:\professer\Gulp\gulpfile.js
# Starting 'callback_error'...
# callback error task~
# 'callback_error' errored after 2.38ms
# Error: task failed~
# at exports.callback_error (E:\professer\Gulp\gulpfile.js:51:8)
# at callback_error (E:\professer\Gulp\node_modules\undertaker\lib\set-task.js:13:15)
# at bound (domain.js:427:14)
# at runBound (domain.js:440:12)
# at asyncRunner (E:\professer\Gulp\node_modules\async-done\index.js:55:18)
# at processTicksAndRejections (internal/process/task_queues.js:79:11)
Copy the code
2. promise
The GULp task also supports accepting promises
exports.promise = () = > {
console.log("promise task~")
// A successful promise is returned via the promise's resolve method
// Once resolve is resolved, the task is finished
// Resolve does not need to be passed as gulp ignores this value
return Promise.resolve()
}
Copy the code
What if the promise fails? Reject
exports.promise_error = () = > {
console.log("promise task~")
return Promise.reject(new Error('promise failed'))}Copy the code
3. async/await
Async and await in ES7 work as well
PS: This can be used if node is 8+
const delay = time= > {
return new Promise((resolve, reject) = > {
setTimeout(resolve, time)
})
}
exports.async = async() = > {await delay(1000)
console.log("async task~")}Copy the code
perform
gulp async
# Using gulpfile E:\professer\Gulp\gulpfile.js
# Starting 'async'...
# async task~
# Finished 'async' after 1.01s
Copy the code
stream
You need to return a stream object in the task function
const fs = require("fs")
exports.stream = () = > {
// Read the file stream object of the file
const readStream = fs.createReadStream('package.json')
// The file stream object that writes the file
const writeStream = fs.createWriteStream('temp.txt')
// File copy is piped from the read into the write
readStream.pipe(writeStream)
// Return readStream
return readStream
}
Copy the code
The entire task is completed when the stream object ends. Because stream objects have an end event, the end event is executed after the file stream has been read. Gulp will know that the task is complete.
Similar to the
exports.end = done= > {
const readStream = fs.createReadStream('package.json')
const writeStream = fs.createWriteStream('temp.txt')
readStream.pipe(writeStream)
// Listen for the end event to execute done
readStream.on('end'.() = > {
done()
})
}
Copy the code
Core working principle of Gulp construction process
Gulp is a stream-based build system. It works by reading the file and then writing it to another file.
const fs = require("fs")
const { Transform } = require('stream')
exports.default = () = > {
// File read stream
const read = fs.createReadStream('normalize.css')
// Write the file to the stream
const write = fs.createWriteStream('normalize.min.css')
// File conversion stream
const transform = new Transform({
transform: (chunk, encoding, callback) = > {
// ★★★ core conversion process realization ★★★
// chunk => the contents read in the stream (Buffer)
// Convert the Buffer array to a string using toString
const input = chunk.toString()
// Replace whitespace characters and CSS comments
// Put the converted result in the output variable
const output = input.replace(/\s+/g.' ').replace(/ / \ \ *. +? \*\//g.' ')
// Callback returns the first error argument, or null if there is no error argument
// output is exported as a result of success
callback(null, output)
}
})
// File copy is piped from read to write
read
.pipe(transform)
.pipe(write)
return read
}
Copy the code
Gulp read stream and write stream API
Gulp provides an API for reading streams and writing streams, which is more powerful and easier to use than node’s API. The transformation flow is mostly provided through standalone plug-ins.
Here’s an example:
- Load a plug-in that compresses CSS
npm install gulp-clean-css
And plug-ins to modify file typesnpm install gulp-rename
- in
gulpfile.js
In writing
const { src, dest} = require('gulp')
const cleanCss = require('gulp-clean-css')
const rename = require('gulp-rename')
exports.default = done= > {
// Read the stream. The argument is the file path. The power is that you can use wildcards to match multiple files
src('src/*.css')
// Compress the code
.pipe(cleanCss())
// Change the file type
.pipe(rename({ extname: '.min.css'}))
// The output stream is the output path
.pipe(dest('dest'))
done()
}
Copy the code
- Run on the command line
gulp
You can see that the corresponding file is generated, is compressed and the name is changed tonormalize.min.css
.