Gulp Getting Started

Source: Internet
Author: User
Tags glob globs

1, Gulp Introduction

Gulpis based onNodejsAutomatic task Runner that she can automate to completeJavaScript,Coffee,Sass, Less,Html/image,CSSfiles such as test, check, merge, compress, format, browser automatic refresh, deployment file generation, and listen to the file after the changes are repeated the specified steps。in the realization, she borrowed from the Unixthe piping of the operating system (Pipethought, the output of the previous level, directly into the back-level input, making it very simple to operate.

Gulp has the following advantages:

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

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

With a minimal API, mastering gulp effortlessly, build your work in the hands of: like a series of streaming pipelines.

Gulp Strict plug-in guides are as concise and high-quality as you would expect.

 

Related website:

Official website: http://gulpjs.com/

Chinese Web: http://www.gulpjs.com.cn/

Plugin: http://gulpjs.com/plugins/

Gitbook:https://wizardforcel.gitbooks.io/gulp-doc/content/2.html

2, gulp use Boot 2.1 Quick Start

  1. Global Installation

Install -G gulp

  2. Install under the project folder root directory

Install Gulp–save-dev

  3. New Gulpfile.js

4. Write the contents of the file and run it

var gulp = require (' Gulp '); Gulp.task (' default ',function() {    console.log (' (Hello World ');});
2.2 Core API

http://www.ydcss.com/archives/424

Let's start with the way gulp.js works. In Gulp , you use Stream (stream) in Nodejs , first get to the streamyou want, and then you can go through the stream 's The pipe () method imports the stream where you want it.

2.3 globs Syntax

  

Match character

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

**

Matching 0 or more directories and their subdirectories in the path needs to appear separately, that is, it cannot have anything else left or right. If it appears at the end, it can also match the file.

?

Matches one character in the file path (does not match the path delimiter)

[...]

Match any one of the characters that appear in the square brackets, when the first character in the square brackets is ^ or!, or any of the other characters that appear in the square brackets, similar to the usage in a JS regular expression

! (Pattern|pattern|pattern)

Matches anything that does not match any of the patterns given in parentheses.

? (Pattern|pattern|pattern)

Match any pattern given in parentheses 0 or 1 times, similar to the one in JS Regular (Pattern|pattern|pattern)?

+ (Pattern|pattern|pattern)

Match any pattern given in parentheses at least 1 times, similar to the one in JS Regular (Pattern|pattern|pattern) +

* (Pattern|pattern|pattern)

Match any pattern given in parentheses 0 or more times, similar to the one in JS Regular (pattern|pattern|pattern) *

@ (Pattern|pattern|pattern)

Matches any given pattern in parentheses 1 times, similar to the one in JS Regular (Pattern|pattern|pattern)

  Take the following 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.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 only a single * * appears alone to match a multilevel directory

?. JS can match a.js,b.js,c.js

A?? 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

2.4 Gulp.task

 Task defines a gulp task

Syntax: Gulp.task (NAME,[,DEPS],FN)

Name: type (required) String specifies the name of the task (there should be no spaces);

Deps: Type (optional) Stringarray, the task that the task depends on (note: The dependent task needs to return the event stream for the current task, refer to the following example)

Gulp.task (' testless ',function() {  return gulp.src ([' less/style.less '])      . Pipe (less ())      . Pipe (Gulp.dest ('./css '));}); Gulp.task (' minicss ', [' testless '],function() {  //  After performing the testless task, perform the MINICSS task  gulp.src ([' Css/*.css '])    . Pipe (Minifycss ())    . Pipe (gulp.dest ('./dist/css ');});

fn: Type (required): Function called by the task plug-in operation;

You can also define a task that is performed by default when a gulp starts running and name the task "default";

Task dependency: If the task is not dependent on each other, the task executes as you write, and if it is dependent, it performs the dependent task first. However, if a task relies on a task that is asynchronous, it is important to note that Gulp does not wait for the asynchronous task to be relied upon to complete, but to proceed with subsequent tasks.

// as long as the default task is performed, it is equivalent to the one,two,three of the three tasks executed gulp.task (' Default ', [' One ', ' two ', ' three ']);

  So what if we want to wait for the asynchronous operation in the asynchronous task to complete before proceeding with the subsequent operation? There are three ways to achieve this:

First: After the asynchronous operation is completed, a callback function is executed to notify Gulp that the asynchronous task is complete, and this callback function is the first parameter of the task function.

Gulp.task (' One ',function(CB) {//CB) provides callbacks for task functions to notify that the task has been completed  //  One is an asynchronous execution of the  task  exec (function() {    console.log (' A is Finish ')    ; // executes a callback that indicates that the asynchronous has completed  },5000);}); // The second task then executes Gulp.task (' One ', [' one '],function() {console.log () after the asynchronous operation in the one task completes.   ' Both is Finish ');});

 Second: A stream object is returned when the task is defined. Applies to the case where the operation Gulp.src gets to the stream.

Gulp.task (' One ',function(CB) {  var stream = gulp.src (' client/**/*.js ')       There are some asynchronous operations in//EXEC ()      . Pipe (Gulp.dext (' Build '))  ; return stream;    }) Gulp.task (' both ', [' one '],function() {  console.log (' Both are done ');});

 Third: Returns a Promise object, such as

var Q = require (' q '); Gulp.task (' one ',function() {  var deferred = q.defer ();   // perform asynchronous Operation  setTimeout (function() {    deferred.resolve ();  }, 1);   return deferred.promise;}); Gulp.task (' one ', [' one '],function() {  console.log (' n ' Done ')});
2.5 GULP.SRC

Syntax: GULP.SRC (Globs,[,options])

The SRC method is to specify the path to the source file that needs to be processed, and gulp draws on the UNIX operating system's pipeline (pipe) idea, the output from the previous level directly into the back-level input, GULP.SEC returns the current file stream to the available plugins.

Globs: Source file match path that needs to be processed. Type (required): String or Stringarray

Options: Type (optional): Object, with three attributes buffer,read,base;

Options.buffer: Type (Boolean) is true by default and set to False, which returns the stream of file.content and does not buffer the file, which is useful when working with large files.

Options.read: Type (Boolean) is true by default, and set to false, the operation to read the file is no longer executed, and NULL is returned

Options.base: Type (String) sets the output path to be stitched backwards based on some part of a path, as shown in the following example:

GULP.SRC (' client/js/**/*.js ')    . Pipe (Minify ())    . Pipe (Gulp.dest (' build ')); Gulp.src (' Client/js/**/*.js ', {base: ' client '}).    pipe (Minify ())    . Pipe (Gulp.dest (' build '));

 Multiple files: Arrays can be used when there are multiple matching patterns

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

  Gulp.dest (Path,[,options])

The Dest method is to specify the path to output after processing the file;

Path: Type (required): String or function specifies the file output path, or defines the function to return the file output path;

Options: Type (optional): Object, with two attributes Cwd,mode;

OPTIONS.CWD type (String) Default: PROCESS.CWD () The path to the working directory, which will be used when the file output path is a relative path;

Options.mode type (String) Default: 0777 Specifies the permissions of the folder being created;

Gulp.src ('./client/templates/*.jade ')    . Pipe (Jade ())    . Pipe (Gulp.dest ('./build/templates '))    . Pipe (Minify ())    . Pipe (Gulp.dest ('./build/minified_templates '));

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

2.7 Gulp.watch

Syntax: Gulp.watch (Glob,[,opts],task) or Gulp.watch (GLOP,[,OPTS,CB])

Note: The watch method is used to listen for file changes, and a modification of the file will perform the specified task.

Glob: Source file match path that needs to be processed. Type (required): String or Stringarray;

OPTs: type (optional): Object specific please see: https://github.com/shama/gaze;

Tasks: Type (required): Stringarray The name array of the task to be performed;

CB (Event): type (optional): function each file changes the execution of the callback functions;

Gulp.task (' watch1 ',function() {  gulp.watch (' less/**/*.less ', [' testless ']);}); Gulp.task (' watch2 ',function() {  gulp.watch (' js/**/*.js ',function(event) {    Console.log (' File ' +event.path+ ' was ' +event.type+ ', running tasks ... ');      } )
3. Common Plug-ins

Delete files and folders 

Del:https://github.com/sindresorhus/del

Merging JS files

Gulp-concat:https://github.com/contra/gulp-concat

Merging CSS Files

Gulp-concat-css

Https://github.com/mariocasciaro/gulp-concat-css

Renaming files

Gulp-rename:https://github.com/hparra/gulp-rename

Compression JS

Gulp-uglify:https://github.com/terinjokes/gulp-uglify

Compress CSS

Gulp-cssnano:https://github.com/ben-eb/gulp-cssnano

Compress pages

Gulp-minify-html:https://github.com/sanfords/gulp-minify-html

Compress photos

Gulp-imagemin:https://github.com/sindresorhus/gulp-imagemin

Automatically open browser

Gulp-open:https://github.com/stevelacy/gulp-open

Gulp-notify

Gulp-notify:https://github.com/mikaelbr/gulp-notify

rely on automatic loading

Gulp-load-plugins

Gulp-load-plugins This plugin can help you automatically load the Gulp plugin in the Package.json file. Let's say you have a file dependency in your Package.json:

{  "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 the Gulp-load-plugins in Gulpfile.js to help us load the plugin:

var gulp = require (' Gulp '); // load the Gulp-load-plugins plugin and run it now var plugins = require (' Gulp-load-plugins ') ();

And then we're going to use both the Gulp-rename and the Gulp-ruby-sass plug-ins, You can use Plugins.rename and plugins.rubysass instead, that is, the original plug-in name to remove the gulp-suffix, and then converted to the hump name.

Automatically refresh pages

Gulp-livereload:https://github.com

Gulp Getting Started

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.