node. JS-based automation Tool Gulp

Source: Internet
Author: User
Tags globs save file stream api

node. JS-based automation Tool GulpWhat is Gulp?

Gulp is a stream-based code-building tool in the front-end development process, and it is the building block of the automation project; she can not only optimize the site resources, but also in the development process a lot of repetitive tasks can be automated using the correct tools, she can not only very happy to write code, and greatly improve our efficiency.

Gulp is a NODEJS-based automated task Runner that automates the testing, checking, merging, compressing, formatting, automatic browser refresh, deployment file generation of JavaScript, coffee, sass, less, html/image, CSS, and more. And listen for files that repeat the specified steps after the change. In the implementation, she borrowed from the Unix operating system pipeline (pipe) thought, the previous level of output, directly into the back-level input, making it very simple to operate.

Flow (Stream)

Flow, in simple terms, is a kind of abstract data processing tool based on object-oriented. In the stream, some basic operations are defined for processing data, such as reading data, writing data, etc., and the programmer is doing all the operations of the stream without worrying about the true flow of data from the other end of the flow. Streams can handle not only files, but also dynamic memory, network data, and many other forms of data.

The gulp is just as simple as the flow and code better than the configured strategy to simplify task writing. This looks like a "jquery" approach, which strings together to create a build task. In the early days of UNIX, the flow already existed. Streams also play an important role in the node. JS ecosystem, similar to *nix, which abstracts almost all of the devices into files, and node abstracts almost all IO operations into stream operations. So writing tasks with Gulp can also be seen as writing tasks with node. js. When using a stream, Gulp removes the intermediate file and writes only the last output to the disk, so the process becomes faster.

Characteristics
    • Easy to use

With code better than the configured strategy, Gulp makes simple tasks simple and complex tasks manageable.

    • Build Fast

With the power of the node. JS Stream, you can quickly build projects and reduce frequent IO operations.

    • Easy to learn

With a minimal API, mastering gulp effortlessly and build your work in the hands of a series of flow pipelines.

    • High quality plug-in

Gulp's strict plug-in guide ensures that the plug-in is as concise and high-quality as you expect.

Installation

First make sure you have the NODEJS environment installed correctly. Then install the Gulp in a global manner:

NPM Install-g Gulp

After you install gulp globally, you also need to install them separately in each project that you want to use Gulp. Switch the directory to your project folder and execute it on the command line:

NPM Install Gulp

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

NPM Install--save-dev Gulp

This completes the installation of the gulp, and the next step is to apply the gulp to the project.

Use of Gulp

1. Create a Gulpfile.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 an example of the simplest Gulpfile.js file content, which defines a default task.

var gulp = require (' gulp '); Gulp.task (' Default ', function () {Console.log (' Hello World ');});

At this point our directory structure is like this:

2. Run the Gulp task

To run the Gulp task, simply switch to the directory where the Gulpfile.js file is located (Windows platforms use a tool such as CMD or power shell), and then execute the Gulp command on the command line, followed by the task name to be executed, gulp, for example Gulp Task1, if you do not specify a task name, the default task with the task named default is executed.

3. Course Practice Environment

(1) Click "File Management" in the editing environment on the right to see the directory structure we have created for you.

(2) Then we can edit the Gulpfile.js file (double-click), edit the completion of the click "Save File";

(3) Finally in the terminal to our project directory, run the Gulp command, so that you can view the results in the terminal.

In addition, in the list of directory entries, we can right-click on the file or directory to operate.

Working style

Before we introduce the Gulp API, let's start with the way gulp.js works. In gulp, using the stream (stream) in the Nodejs, first get to the desired stream, and then you can use the stream's pipe () method to import the stream into the place you want, such as the Gulp plug-in, after the plug-processed stream and can continue to import into other plugins , of course, you can also write the stream to a file. So gulp is a stream for the media, it does not require frequent generation of temporary files, which is one of the reasons we apply gulp.

Gulp use process is generally: first through the GULP.SRC () method to get to the file stream to be processed, and then the file stream through the pipe method to import into the gulp plug-in, and finally after the plug-in processing flow through the pipe method to import into the Gulp.dest (), The Gulp.dest () method writes the contents of the stream to a file. For example:

var gulp = require (' gulp '); Gulp.src (' script/jquery.js ')//Get Stream API. Pipe (Gulp.dest (' dist/foo.js ')); Write-and-file API

We will explain the gulp API to our classmates in this chapter, including GULP.SRC (), Gulp.task (), Gulp.dest (), Gulp.watch (), Gulp.run ().

Matching rules for globs

We'll focus on the matching rules of the globs used by gulp and some file matching techniques, and we'll use these rules in the following lessons.

The gulp internal uses the Node-glob module to implement its file matching function. We can use the following special characters to match the file we want:

Match       Description \*                              Matches 0 or more characters in a file path, but does not match the path delimiter,                                Unless the path delimiter appears at the end **                              matches 0 or more directories in the path and their subdirectories, which need to appear separately,                                 that it can't have anything else around it. If it appears at the end, you can also match the file.?                             &nbSP; match one of the characters in the file path (does not match the path delimiter) [...]                            match any one of the characters that appear in square brackets when the first character in the square brackets is ^ or!,                                 does not match any of the other characters appearing in square brackets,                                 similar to the usage in JS regular expressions! (Pattern|pattern|pattern)      matches anything that doesn't match any of the patterns given in parentheses? (Pattern|pattern|pattern)      match any pattern given in parentheses 0 or 1 times,                                 similar to JS regular (Pattern|pattern|pattern)? + (Pattern|pattern|pattern)      matches any of the patterns given in parentheses at least 1 times,                                Similar to JS regular (Pattern|pattern|pattern) +* (pattern|pattern|pattern)      match any pattern given in parentheses 0 or more times,                                 similar to JS Regular (Pattern|pattern|pattern) *@ (pattern |pattern|pattern)      match any pattern given in parentheses 1 times,                                 similar to JS regular (Pattern|pattern|pattern)

Here's an example to deepen your understanding

\* can match a.js,x.y,abc,abc/, but cannot match a/b.js*.* can match 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/a.b, 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.jsa/* */z can match a/z,a/b/z,a/b/c/z,a/d/g/h/j/k/za/**b/z can match a/b/z,a/sb/z, but cannot match a/x/sb/z, because only a single * * appears to match the multilevel directory? JS can match A.js,b.js,c.jsa?? Can match a.b,abc, but cannot match ab/, because it does not match the path delimiter [xyz].js only matches x.js,y.js,z.js, does not match xy.js,xyz.js, etc., the entire bracket represents only one character [^xyz].js can match a.js,b.js , c.js, etc., cannot match x.js,y.js,z.js
Get stream

The Gulp.src () method is used to get the stream, but note that the content in this stream is not the original file stream, but rather a virtual file object stream (Vinyl files), which stores the path, file name, and content of the original file. Its syntax is:

GULP.SRC (globs[, Options]);

The globs parameter is a file-matching pattern (similar to a regular expression), used to match the file path (including the file name) and, of course, to specify a specific file path directly. When there are multiple matching patterns, the parameter can be an array, and the type is string or array. We've talked about Globs's matching rules in the previous section, which is not detailed here.

Arrays can be used when there are multiple matching patterns

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

Options is an optional parameter. The options parameters are as follows:

Options.buffer

Type: Boolean default value: True

If the item is set to False, the file.contents will be returned as stream instead of the file buffer. This can be useful when dealing with large files. Note: Plugins may not implement support for stream.

Options.read

Type: Boolean default value: True

If the entry is set to False, then File.contents returns a null value (NULL), which means that the file is not read.

Options.base

Type: String that sets the output path to be stitched backwards based on some part of a path.

For example, imagine that in a directory with a path of Client/js/somedir, there is a file called Somefile.js:

GULP.SRC (' client/js/**/*.js ')//Match ' client/js/somedir/somefile.js ' now the value of ' base ' is ' client/js/'. Pipe (Minify ()). Pipe (gu    Lp.dest (' build ')); Write ' build/somedir/somefile.js ' to replace ' client/js/' with Build gulp.src (' Client/js/**/*.js ', {base: ' client '})//Base value ' CLI '    Ent '. Pipe (Minify ()). Pipe (Gulp.dest (' Build ')); Write ' build/js/somedir/somefile.js ' to replace ' client ' with build
Write a file

The Gulp.dest () method is used to write a file with the following syntax:

Gulp.dest (Path[,options])

Path is the way to write to the file;

Options is an optional parameter object and the following is the option parameter:

Options.cwd

Type: String default value: PROCESS.CWD ()

The CWD parameter of the output directory is valid only when the given output directory is relative to the path.

Options.mode

Type: String default value: 0777

An octal permission character that defines the permissions for all directories created in the output directory.

var gulp = require (' gulp '); Gulp.src (' script/jquery.js ')//Get stream. Pipe (gulp.dest (' dist/foo.js ')); Write and put files

The following is the relationship between the generated file path and the path parameter that we passed to the _gulp.dest () _ Method. The file path generated by _gulp.dest (path) is the part of the path that we passed in with the _path_ parameter followed by a wildcard character starting in _gulp.src () _. For example:

var gulp = Reruire (' gulp ');//The portion of the path with the wildcard character starting to appear is **/*.jsgulp.src (' script/**/*.js '). Pipe (Gulp.dest (' dist ')); The last file path generated is dist/**/*.js//if **/*.js matches to a file that is jquery/jquery.js, the resulting file path is Dist/jquery/jquery.js

After the file stream is written to the file with Gulp.dest (), the file stream can still be used.


More examples and online exercises can be seen here:
http://www.hubwiz.com/course/562089cb1bc20c980538e25b/


node. JS-based automation Tool Gulp

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: info-contact@alibabacloud.com 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.