Details about the use and skills of the front-end build tool gulpjs, and details about gulpjs

Source: Internet
Author: User
Tags globs

Details about the use and skills of the front-end build tool gulpjs, and details about gulpjs

Gulpjs is a front-end build tool. Compared with gruntjs, gulpjs does not need to write a lot of complicated configuration parameters. APIs are also very simple and easy to learn, in addition, gulpjs uses stream in nodejs to read and operate data, which is faster. If you have not used a front-end build tool or think gruntjs is too difficult to use, try gulp.

1. Install gulp

First, make sure that you have correctly installed the nodejs environment. Then install gulp globally:

npm install -g gulp

After you install gulp globally, you also need to install it once in each project that uses gulp. Switch the directory to your project folder and execute the following command in the command line:

npm install gulp

If you want to write gulp into the dependency of the project package. json file during installation, you can add -- save-dev:

npm install --save-dev gulp

This completes the installation of gulp. After installing gulp globally, you need to install gulp locally in the project. If you are interested, refer to the answer from someone on stackoverflow: why-do-we-need-to-install-gulp-globally-and-locally, what-is-the-point-of-double-install-in-gulp. It is generally for the flexibility of the version, but if you don't understand it, you don't have to worry too much about it. You just need to know that we usually want to do this.

2. Start to use gulp

2.1 create a gulpfile. js File

Just as gruntjs requires a Gruntfile. js file, gulp also needs a file as its main file. In gulp, this file is called gulpfile. js. Create a new file named gulpfile. js and put it in your project directory. The next thing to do is to define our task in the gulpfile. js file. The following is a simple example of the content of the gulpfile. js file. It defines a default task.

var gulp = require('gulp');gulp.task('default',function(){ console.log('hello world');});

The directory structure is as follows:

├── gulpfile.js ├── node_modules │ └── gulp └── package.json

2.2 run the gulp task

To run the gulp task, you only need to switch to the storage gulpfile. directory of the js file (for windows platforms, use cmd or Power Shell tools), and then execute the gulp command in the command line. The name of the task to be executed can be added after the gulp, for example, if the task name is not specified for gulp task1, the default task named default is executed.

3. Introduction to gulp APIs

To use gulp, you only need to know four APIs: gulp. task (), gulp. src (), gulp. dest (), gulp. watch (), so it is easy to grasp, but there are a few places to understand thoroughly, I will explain one by one below. To avoid misunderstanding, we recommend that you read the official documents first.

3.1 gulp. src ()

Before introducing this API, let's take a look at the difference between Grunt. js and Gulp. js working methods. Grunt runs its workflow in the media of files. For example, after a task is executed in Grunt, the result is written to a temporary file, then, you can execute other tasks on the basis of the temporary file content. After the execution is complete, the results are written to the temporary file, and then continue to execute other tasks on the basis of this... this is the case.

In Gulp, stream (stream) in Nodejs is used. First, obtain the required stream, and then the stream can be imported to the desired place through the pipe () method of stream, for example, in the Gulp plug-in, the stream processed by the plug-in can be imported to other plug-ins, and the stream can also be written to files. Therefore, Gulp uses stream as the media and does not need to generate temporary files frequently. This is one reason why Gulp is faster than Grunt. Back to the topic, gulp. the src () method is used to get the stream, but note that the content in the stream is not the original file stream, but a virtual file object stream (Vinyl files ), this virtual file object stores the path, file name, content, and other information of the original file, which we do not need to understand at the moment, you only need a simple understanding and can use this method to read the files you need to operate on. Its syntax is:

gulp.src(globs[, options])

The globs parameter is a file matching mode (similar to a regular expression) used to match the file path (including the file name). Of course, you can specify a specific file path here. When multiple matching modes exist, this parameter can be an array.

Options is an optional parameter. We usually do not need to use it.

Next we will focus on the glob matching rules used by Gulp and some file matching techniques.

Gulp uses the node-glob module to implement file matching. We can use the following special characters to match the desired file:

• * Matches 0 or more characters in the file path, but does not match the path separator, unless the path separator appears at the end

• ** Match zero or multiple directories and Their subdirectories in the path, which must appear separately, that is, there cannot be anything else on the left or right. If it appears at the end, the file can also be matched.

•? Match one character in the file path (path separator not matched)

• [...] Match any one of the characters in square brackets. When the first character in square brackets is ^ or! It indicates that none of the other characters in square brackets are matched, similar to the usage in js regular expressions.

•! (Pattern | pattern) matches any pattern specified in the brackets.

•? (Pattern | pattern) matches any of the given patterns in parentheses 0 or 1 times, similar to (pattern | pattern) in js regular expressions )?

• + (Pattern | pattern) matches any given pattern in brackets at least once, similar to (pattern | pattern) +

• * (Pattern | pattern) matches any given pattern in brackets 0 or multiple times, similar to (pattern | pattern) * in js regular expressions )*

• @ (Pattern | pattern) matches any given pattern in brackets once, similar to pattern | pattern in js regular expressions)

The following is a series of examples to deepen understanding.

• * Matching a. js, x. y, abc, abc/, but not a/B. js

• *. * Matches a.js, style.css, a. B, x. y

•*/*/*. Js can match a/B/c. js, x/y/z. js, cannot match a/B. js, a/B/c/d. js

• ** Can match abc, a/B. js, a/B/c. js, x/y/z, x/y/z/. b. It can be used to match all directories and files.

• **/*. Js can match foo. js, a/foo. js, a/B/foo. js, a/B/c/foo. js

• A/**/z can match a/z, a/B/z, a/B/c/z, a/d/g/h/j/k/z

• A/** B/z can match a/B/z, a/sb/z, but cannot match a/x/sb/z, because the multi-level directory can be matched only when a single ** appears separately

•?. Js can match a. js, B. js, and c. js.

• ?? Can match a. B, abc, but cannot match AB/, because it does not match the path Separator

• [Xyz]. js can only match x. js, y. js, z. js, but does not match xy. js, xyz. js, etc. The brackets only represent one character.

• [^ Xyz]. js can match a. js, B. js, c. js, etc. It cannot match x. js, y. js, z. js

An array can be used when multiple matching modes exist.

// Use arrays to match multiple files, such as gulp. src (['js/*. js', 'css/*. css ',' *. html '])

Another advantage of using arrays is that you can easily use the exclusion mode, and add it before a single matching mode in the array! This is the exclusion mode. It will exclude this match from the matching results. Note that the exclusion mode cannot be used in the first element of the array.

Gulp. src ([*. js ,'! B *. js']) // match all js files, but exclude the js file gulp. src (['! B *. js', *. js]) // No files are excluded, because the exclusion mode cannot appear in the first element of the array.

You can also use the expand mode. The expansion mode uses curly brackets as the delimiters. Based on the content in the brackets, the expansion mode is displayed in multiple modes, and the final matching result is the result obtained by adding all the expanded modes. The example is as follows:

• A {B, c} d: abd, acd

• A {B,} c will be held at the abc, ac

• A {0 .. 3} d: a0d, a1d, a2d, and a3d

• A {B, c {d, e} f} g: abg, acdfg, and acefg

• A {B, c} d {e, f} g will be exhibited at abdeg, acdeg, abdeg, abdfg

3.2 gulp. dest ()

The gulp. dest () method is used to write files. Its syntax is:


Path indicates the path of the file to be written.

Options is an optional parameter object.

To use the method gulp. dest (), you must understand the relationship between the passed path parameters and the final file.

The usage process of gulp is generally like this: first, use gulp. the src () method gets the file stream we want to process, and then imports the file stream through the pipe method into the plug-in of gulp, finally, the stream processed by the plug-in is imported to gulp through the pipe method. in dest (), gulp. the dest () method writes the content in the stream to the file. The first thing we need to figure out here is that we give it to gulp. the path parameter passed in by dest () can only be used to specify the directory of the file to be generated, but cannot specify the file name to be generated, the file name used to generate the file is the file name of the file stream imported to it, so the generated file name is determined by the file stream imported to it, even if we input a path parameter with a file name, it will regard the file name as a directory name, for example:

Var gulp = require ('gulp'); gulp. src ('script/jquery. js '). pipe (gulp. dest ('dist/foo. js '); // The final generated file path is dist/foo. js/jquery. js instead of dist/foo. js

To change the file name, use the plug-in gulp-rename.

The following describes the relationship between the generated file path and the path parameters passed in to the gulp. dest () method.

The file path generated by gulp. dest (path) is the part of the path that begins to appear after the passed path parameter plus the wildcards in gulp. src. For example:

Var gulp = reruire ('gulp'); // The part of the path with the wildcard starting to appear is **/*. jsgulp. src ('script /**/*. js '). pipe (gulp. dest ('dist'); // The Last generated file path is dist /**/*. js // If **/*. the file matched by js is jquery/jquery. js, the generated file path is dist/jquery. js

More examples

Gulp. src ('script/aveon. js') // No wildcard characters. pipe (gulp. dest ('dist'); // The Last generated file path is dist/aveon. js // The part of the path that starts to appear with a wildcard character is **/underscore. jsgulp. src ('script/**/underscore. js ') // assume that the matched file is script/util/underscore. js. pipe (gulp. dest ('dist'); // the path of the last generated file is dist/util/underscore. jsgulp. src ('script/* ') // The path in which the wildcard appears is * // assume that the matched file is script/zepto. js. pipe (gulp. dest ('dist'); // The Last generated file path is dist/zepto. js

By specifying the base attribute of the parameter in the gulp. src () method, we can flexibly change the file path generated by gulp. dest.

When the base attribute is not configured in the gulp. src () method, the default value of base is the path before the wildcard begins to appear. For example:

Gulp. src ('app/src/**/*. css ') // The base value is app/src.

Gulp. the file path rules generated by dest () can also be understood. replace gulp with the path passed in by dest. the base path in src () to obtain the path of the generated file.

Gulp. src ('app/src /**/*. css ') // at this time, the base value is app/src, that is, its base path is app/src //. Set this pattern to match the file app/src/css/normal.css. pipe (gulp. dest ('dist') // Replace the base path with dist to get the dist/css/normal.css

Therefore, after the base path is changed, the file path generated by gulp. dest () will also change.

Gulp. src (script/lib /*. js) // The base parameter is not configured. The default base path is script/lib // assume that the matched file is script/lib/jquery. js. pipe (gulp. dest ('built') // The generated file path is build/jquery. jsgulp. src (script/lib /*. js, {base: 'script'}) // The base parameter is configured. The base path is script // assume that the matched file is script/lib/jquery. js. pipe (gulp. dest ('built') // the file path generated at this time is build/lib/jquery. js

After the file stream is written into the file using gulp. dest (), the file stream can still be used.

3.3 gulp. task ()

The gulp. task method is used to define a task. Orchestrator is used internally. Its syntax is as follows:

gulp.task(name[, deps], fn)

Name indicates the task name.

Deps is another task that the defined task depends on. It is an array. The defined task is executed only after all dependent tasks are executed. If no dependency exists, you can omit this parameter.

Fn is a task function. We write all the code to be executed. This parameter is also optional.

Gulp. task ('mytask', ['array', 'of', 'task', 'names'], function () {// define a dependency task // Do something });

The gulp. task () API is easy to explain, but you need to know how to control the execution sequence of tasks when executing multiple tasks.

You can use task dependencies to execute multiple tasks in gulp. For example, if I want to execute one, two, and three tasks, we can define an empty task, then, use the three tasks as the dependencies of the empty task:

// As long as the default task is executed, it is equivalent to executing gulp for one, two, and three tasks. task ('default', ['one', 'two', 'three]);

If there is no dependency between tasks, the tasks are executed in the order you write. If there is dependency, the dependent tasks are executed first.

However, if a task is dependent on an asynchronous task, you must note that gulp will not wait for the dependent asynchronous task to complete, but will continue to execute subsequent tasks. For example:

Gulp. task ('one', function () {// one is an asynchronous execution task setTimeout (function () {console. log ('one is done')}, 5000) ;}); // although the two task depends on the one task, however, it does not wait until the asynchronous operation in the one task is completed before executing gulp. task ('two', ['one'], function () {console. log ('two is done ');});

In the preceding example, when we execute a two task, we will first execute the one task, but will not wait until the asynchronous operation in the one task is completed before the two task is executed, but will then execute the two task. Therefore, the two task will be executed before the asynchronous operations in one task are completed.

What should we do if we want to wait until the asynchronous operation in the asynchronous task is completed before executing the subsequent task?

There are three methods to achieve this:

First, after the asynchronous operation is complete, execute a callback function to notify gulp that the asynchronous task has been completed. This callback function is the first parameter of the task function.

Gulp. task ('one', function (cb) {// cb is the callback provided by the task function to notify the task that it has been completed. // one is an asynchronous execution task setTimeout (function () {console. log ('one is done'); cb (); // executes the callback, indicating that the asynchronous task has been completed}, 5000 );}); // at this time, the two task will execute gulp after completing the asynchronous operation in the one task. task ('two', ['one'], function () {console. log ('two is done ');});

Second, a stream object is returned when a task is defined. This method is applicable when the task is the stream obtained through the gulp. src operation.

Gulp. task ('one', function (cb) {var stream = gulp. src ('client /**/*. js '). pipe (dosomething () // dosomething () has some asynchronous operations. pipe (gulp. dest ('built'); return stream;}); gulp. task ('two', ['one'], function () {console. log ('two is done ');});

Third: return a promise object, such

Var Q = require ('q'); // a well-known asynchronous processing library ('one', function (cb) {var deferred = q. defer (); // perform some asynchronous operations setTimeout (function () {deferred. resolve (); }, 5000); return deferred. promise;}); gulp. task ('two', ['one'], function () {console. log ('two is done ');});

Gulp. task () is the process of processing an asynchronous task.

3.4 gulp. watch ()

Gulp. watch () is used to monitor file changes. When the file changes, we can use it to execute corresponding tasks, such as file compression. Its syntax is[, opts], tasks)

Glob is the file matching mode to be monitored. Its rules and usage are the same as that in the gulp. src () method.

Opts is an optional configuration object.

Task is the task to be executed after the file changes, as an array

gulp.task('uglify',function(){ //do something});gulp.task('reload',function(){ //do something});'js/**/*.js', ['uglify','reload']);

Gulp. watch () has another usage method:[, opts, cb])

The glob and opts parameters are the same as the first method.

The cb parameter is a function. Whenever the monitored file changes, this function is called and an object is passed in to it. This object contains information about the file changes. The type attribute is of the changed type, it can be added, changed, deleted; path. The attribute is the path of the file that has changed.

Gulp. watch ('js /**/*. js', function (event) {console. log (event. type); // change the type added to add, deleted to delete, changed to change the console. log (event. path); // path of the changed file });

4. Some common gulp plug-ins

Although the number of gulp plug-ins is not as large as grunt, it can be said that there are all kinds of plug-ins. The following lists some commonly used plug-ins.

4.1 automatically load plug-ins

Use gulp-load-plugins


npm install --save-dev gulp-load-plugins

To use the gulp plug-in, we must first use require to load the plug-in. If we want to use a lot of plug-ins, then our gulpfile. js file may start with this:

Var gulp = require ('gulp'), // some gulp plug-ins, abcd these names are only used for example a = require ('Gulp-'), B = require ('Gulp-B '), c = require ('Gulp-C'), d = require ('Gulp-d '), e = require ('Gulp-e'), f = require ('Gulp-F'), g = require ('Gulp-G '), // more plug-ins... z = require ('Gulp-Z ');

Although there is no problem, it will make our gulpfile. js file very lengthy and uncomfortable. The gulp-load-plugins plug-in is used to solve this problem.

The gulp-load-plugins plug-in can automatically help you load the gulp plug-in the package. json file. For example, assume that the dependency in your package. json file is as follows:

{ "devDependencies": { "gulp": "~3.6.0", "gulp-rename": "~1.2.0", "gulp-ruby-sass": "~0.4.3", "gulp-load-plugins": "~0.5.1" }}

Then we can use gulp-load-plugins in gulpfile. js to load the plug-in:

Var gulp = require ('gulp'); // load the gulp-load-plugins plug-in and immediately run it var plugins = require ('Gulp-load-ins ')();

Then we can use plugins when using the gulp-rename and gulp-ruby-sass extensions. rename and plugins. this is replaced by rubySass, that is, the original plug-in name removes the gulp-prefix, and then converts it to the hump name.

In essence, the gulp-load-plugins are converted as follows:

plugins.rename = require('gulp-rename');plugins.rubySass = require('gulp-ruby-sass');

Gulp-load-plugins does not load all the gulp plug-ins in package. json at the beginning, but loads the plug-in when we need to use a plug-in.

The last thing to note is that gulp-load-plugins use your package. json file to load the plug-in, so you must ensure that the plug-in you need to automatically load has been written into the package. json file, and these plug-ins have been installed.

4.2 rename

Use gulp-rename


npm install --save-dev gulp-rename

Used to rename files in a file stream. Use gulp. when writing a file using the dest () method, the file name uses the file name in the file stream. To change the file name, you can use the gulp-rename plug-in to change the file name in the file stream.

Var gulp = require ('gulp'), rename = require ('Gulp-rename'), uglify = require ("gulp-uglify"); gulp. task ('rename', function () {gulp. src ('js/jquery. js '). pipe (uglify () // compression. pipe (rename ('jquery. min. js ') // jquery. rename js to jquery. min. js. pipe (gulp. dest ('js'); // for more powerful usage of gulp-rename, see });

4.3. js File compression

Use gulp-uglify


npm install --save-dev gulp-uglify

The uglify engine is used to compress js files.

Var gulp = require ('gulp'), uglify = require ("gulp-uglify"); gulp. task ('minify-js', function () {gulp. src ('js /*. js') // The js file to be compressed. pipe (uglify () // use uglify for compression. For more configurations, see :. pipe (gulp. dest ('dist/js'); // compressed path });

4.4 css file Compression

Use gulp-minify-css

npm install --save-dev gulp-minify-css

This plug-in can be used to compress css files.

Var gulp = require ('gulp'), minifyCss = require ("gulp-minify-css"); gulp. task ('minify-css ', function () {gulp. src ('css /*. css ') // the css file to be compressed. pipe (minifyCss () // compress css. pipe (gulp. dest ('dist/css '));});

4.5 html file Compression

Use gulp-minify-html


npm install --save-dev gulp-minify-html

Used to compress html files

Var gulp = require ('gulp'), minifyHtml = require ("gulp-minify-html"); gulp. task ('minify-html ', function () {gulp. src ('html /*. html ') // The html file to be compressed. pipe (minifyHtml () // compression. pipe (gulp. dest ('dist/html '));});

4.6 js Code check

Use gulp-jshint
Installation: npm install -- save-dev gulp-jshint
Used to check js Code

Var gulp = require ('gulp'), jshint = require ("gulp-jshint"); gulp. task ('json', function () {gulp. src ('js /*. js '). pipe (jshint ()). pipe (jshint. reporter (); // output check result });

4.7 file Merging

Use gulp-concat


npm install --save-dev gulp-concat

It is used to merge multiple files into one file. We can use it to merge js or css files, which can reduce the number of http requests on the page.

Var gulp = require ('gulp'), concat = require ("gulp-concat"); gulp. task ('concat', function () {gulp. src ('js /*. js') // the file to be merged. pipe (concat ('all. js ') // merge the matched js file and name it "all. js ". pipe (gulp. dest ('dist/js '));});

4.8 less and sass Compilation

Less uses gulp-less,


npm install --save-dev gulp-less
var gulp = require('gulp'), less = require("gulp-less"); gulp.task('compile-less', function () { gulp.src('less/*.less') .pipe(less()) .pipe(gulp.dest('dist/css'));});

Sass uses gulp-sass


npm install --save-dev gulp-sass
var gulp = require('gulp'), sass = require("gulp-sass"); gulp.task('compile-sass', function () { gulp.src('sass/*.sass') .pipe(sass()) .pipe(gulp.dest('dist/css'));});

4.9 Image Compression

You can use the gulp-imagemin plug-in to compress jpg, png, gif, and other images.


npm install --save-dev gulp-imagemin
Var gulp = require ('gulp'); var imagemin = require ('Gulp-imagemin'); var pngquant = require ('imagemin-pngquant '); // png Image Compression plug-in gulp. task ('default', function () {return gulp. src ('src/images /*'). pipe (imagemin ({progressive: true, use: [pngquant ()] // use pngquant to compress png images })). pipe (gulp. dest ('dist '));});

The use of gulp-imagemin is a little complicated, and it also has many plug-ins. We recommend that you go to its project homepage to see the documentation.

4.10 automatic refresh

Use the gulp-livereload plug-in


npm install --save-dev gulp-livereload

When the code changes, it can help us automatically refresh the page

It is best to use this plug-in with Google chrome, and to install the livereload chrome extension plug-in. If you cannot download the plug-in, please use FQ on your own.

Var gulp = require ('gulp'), less = require ('Gulp-less '), livereload = require ('Gulp-livereload'); gulp. task ('less ', function () {gulp. src ('less /*. less '). pipe (less ()). pipe (gulp. dest ('css ')). pipe (livereload () ;}); gulp. task ('Watch ', function () {livereload. listen (); // call the gulp method of listen () here. watch ('less /*. less ', ['less']);});

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.