Gulp Quick Start

Source: Internet
Author: User
Tags glob

Gulp Quick Start

Because I have been recommended gulp, said he here good where good. Actually, it's enough for me. Grunt familiar with the fact that his configuration is not difficult, when it comes to efficiency if you really want to complete packaging on-line and don't care about a few seconds, for the project is the key to online efficiency, but offline efficiency as long as it is not unbearable to the page not too many problems. However, it is necessary to use the Gulp in person before judging the merits and demerits between him and grunt. No nonsense, directly on the instance.

I have built a front-end directory structure, the following examples are based on this directory structure. Dest is our packaging compression results save directory, now is empty. After each instance is completed, we will clear the Dest directory to ensure that the result of the next instance corresponds to the instance code.

  

1. The first Simple gulp package

  1) need to install Nodejs: http://www.cnblogs.com/chuaWeb/p/nodejs-npm.html

My Nodejs project directory is F:\chuaNodejs (all subsequent relative paths are relative to this directory)

  2) Create the Package.json file , which can be created using the NPM init command. Then the devdependencies in which the gulp related plug-in dependencies are included. My package.json is like this.

1 {2   "name": "My-gulp", 3   "version": "1.0.0", 4   "description": "Demo", 5   "dependencies": {6     " Express ":" 3.x "7   }, 8   " Devdependencies ": {9     " Gulp-clean ":" ^0.3.2 ","     Gulp ":" ^3.9.1 ", one by one     " Gulp-concat ":" ^2.6.0 ","     gulp-mini-css ":" ^0.0.3 ","     gulp-uglify ":" ^1.5.3 ","     Gulp-requirejs-optimize ":" ^0.3.2 "   },16"   scripts ": {"     test ":" Echo \ "Error:no Test specified\" && exit 1 "   },19   " author ":" Chua ","   License ":" ISC "21}

As we add the plugin installed with NPM, the content changes.

command line to Nodejs directory (requires system administrator privileges, or error in subsequent procedures) Install Gulp as a project development dependency (Devdependencies, of course, can also be installed in other ways): NPM install--save-dev Gulp

Gulp has a lot of official plugins to check the installation: http://gulpjs.com/plugins/.

  But the following plug-ins are basically used, can be installed first

Gulp: This must be installed, without it, other components are not available (note that the watch component is integrated directly into the gulp without the need for additional watch components)

gulp-mini-css : Compression CSS uses the

gulp-uglify: Compress, confuse JS file with

  3) Build a gulpfile.js in the Nodejs project directory, the contents of which are

1 var gulp = require (' Gulp '), 2     mincss = require (' Gulp-mini-css '), 3     uglify = require (' gulp-uglify '); 4  5 var Src_css = './src/css ', 6     dest_css = './dest/css ', 7     src_js = './src/js ', 8     dest_js = './dest/js '; 9 gulp.ta SK (' Mincss ', function () {     gulp.src (src_css+ '/**/*.css ')         . Pipe (Mincss ())         . Pipe (Gulp.dest (dest_ CSS); Gulp.task (' Minjs ', function () {     gulp.src (src_js+ '/**/*.js ')         . Pipe (Uglify ())         . Pipe (Gulp.dest (DEST_JS)); Gulp.task (' Watch ', function () {     gulp.watch (src_css+ '/**/*.css ', [' Mincss ]),     gulp.watch (src_js+ '/**/*.js ', [' Minjs ']), and Gulp.task (' Default ', function () {     Gulp.run (' Minjs ', ' mincss ');     gulp.run (' Watch '); 30});

You can see that it is similar to the Nodejs code.

  4) command line run: Gulp

Execution results

  

We can see the js/css of SRC is packed into the corresponding Dest folder.

Note: The Gulp command and gulp default are equivalent. And this time the monitoring task is always executed, and whenever there is a corresponding file changes, then the corresponding task will be carried out.

  5) Source Code Analysis:

1//Register a task called MINCSS, command line Gulp MINCSS can run this task 2//need to explain that the code "*" represents a layer of files, and "* *" means to recursively its subfolders 3 gulp.task (' Mincss ', function () { 4     gulp.src (src_css+ '/**/*.css ')//returns all (including subfolders) under src/css/. css file stream; gulp.src (str) returned a readable STREAM5         . Pipe ( MINCSS ())//Perform GULP-MINI-CSS component tasks, compress all CSS file streams 6         . Pipe (Gulp.dest (DEST_CSS));//writes the file stream to the corresponding path in the COMPRESS/CSS; Gulp.dest (str) returns a writable stream7});

1//Register the task named Watch 2 gulp.task (' Watch ', function () {3     gulp.watch (src_css+ '/**/*.css ', [' mincss ']);//monitoring src/css/ All the. css files under, if there is a change, execute the name ' mincss ' Task 4     gulp.watch (src_js+ '/**/*.js ', [' minjs ']);//monitor all the. js files under the src/css/, and if there are any changes, execute the name ' Minjs ' Task 5});

1//Each gulpfile.js should have a dafault task, it is the default task portal, when running gulp actually just invoke the task (to invoke other tasks) 2 Gulp.task (' Default ', function () {3     Gulp.run (' Minjs ', ' mincss ');//immediately perform the tasks of ' minjs ', ' mincss '; gulp.run (tasks) means running the corresponding task 4     gulp.run (' watch ');//immediately execute ' Watch ' Task 5});

Compared to grunt, it's really easier to get started.

2. Merging compression

There are times when you need to merge multiple files to reduce requests, and you need to compress them. This can be done using uglify and concat. So also download the concat plugin: npm install Gulp-concat--save-dev

Gulpfile.js Code

1 var gulp = require (' Gulp '), 2     uglify = require (' Gulp-uglify '), 3     concat = require (' Gulp-concat '); 4  5 var sr C_js = './src/js ', 6     dest_js = './dest/js '; 7  8 Gulp.task (' Minjs ', function () {9     gulp.src (src_js+ '/**/*.js ') )         pipe (uglify ())//compression one by one         . Pipe (Concat ("All.min.js"))//merger of         Pipe (Gulp.dest (DEST_JS)); 13}); 14 15 Gulp.task (' Watch ', function () {     gulp.watch (src_js+ '/**/*.js ', [' minjs ']);//monitor all the. js files under the src/css/, and if there are any changes, execute the name ' Minjs ' mission '); Gulp.task (' Default ', [' minjs ', ' Watch ']);

Here the files are compressed in alphabetical order and layered in deep order into the all.min.js.

Here we see a variety of uses for Gulp.task, Gulp.task (name[, Deps], FN), and Deps is an array of task lists that are completed before your current task runs. Detailed reference: http://www.gulpjs.com.cn/docs/api/

If you want to compress in the order specified, you need to perform a list of files for GULP.SRC, and Gulp will compress the elements in the file list array.

Gulpfile.js Source

1 var gulp = require (' Gulp '), 2     uglify = require (' Gulp-uglify '), 3     concat = require (' Gulp-concat '); 4  5 var sr C_js = './src/js ', 6     dest_js = './dest/js '; 7  8 Gulp.task (' Minjs ', function () {9     gulp.src ([src_js+ '/bootstr Ap.min.js ', src_js+ '/jquery.js '])//Compress bootstrap first, then compress Jquery10         . Pipe (Uglify ()) one by one         . Pipe (Concat (" All.min.js ") (         gulp.dest (DEST_JS)), and Gulp.task (' Watch ', function () {16     

3. Watch Event Monitoring

The watch component is included in the gulp and is not allowed to be downloaded separately.

We've used the basic usage of watch in the first instance: Gulp.watch (glob,tasks)

Now take a look at another usage: gulp.watch (glob,callback)

Gulpfile.js Source

1 var gulp = require (' Gulp '), 2   uglify = require (' Gulp-uglify '), 3   notify = require ("Gulp-notify"); 4  5 gulp.t Ask (' Minjs ', function () {6   gulp.src (' src/main.js ') 7     . Pipe (Uglify ()) 8     . Pipe (Gulp.dest ("dest/")); 9}); Gulp.task (' Watch ', function () {   gulp.watch (' Src/main.js ', function (e) {     //e has two properties type/path14     if (E.type = = "Changed") {//added, changed, or deleted15       gulp.run ("Minjs");       Console.log (E.type + ":" + E.path);}18   }); Gulp.task (' Default ', ["Minjs", ' Watch ']);

You can see that the function parameter (event) e has two attributes of type and path. We can do some custom services based on their values.

  

Another very good feature of Gulp.watch () is the return of the Watcher object. Use Watcher to listen for additional events or add files to watch.

See another copy of the Gulpfile.js code

1 var gulp = require (' Gulp '), 2   uglify = require (' Gulp-uglify '), 3   notify = require ("Gulp-notify"); 4  5 gulp.t Ask (' Minjs ', function () {6   gulp.src (' src/main.js ') 7     . Pipe (Uglify ()) 8     . Pipe (Gulp.dest ("dest/")); 9}); Gulp.task (' Watch ', function () {   var watcher = Gulp.watch (' Src/main.js ', ["Minjs"]),   Watcher.on (' Change ', function (e) {     if (E.type = = "Changed") {       Console.log (E.type + ":" + e.path); +     }17   }); 18} ); Gulp.task (' Default ', [' minjs ', ' Watch ']);

In addition to the Change event, you can listen to many other events:

End is triggered at the end of watcher (this means that the task or callback will not execute when the file changes)

Error is triggered when error occurs

Ready is triggered when a file is found and is being monitored

NoMatch triggers when Glob does not match to any file

The Watcher object also contains some methods that can be called:

Watcher.end () Stop watcher (to stop execution of subsequent tasks or callback functions)

Watcher.files () returns a list of watcher listening files

Watcher.add (glob) adds the file that matches the specified glob to the Watcher (also accepts the optional callback when the second parameter)

Watcher.remove (filepath) removing individual files from watcher

4. Some gulp important plugins

  Gulp: This must be installed, without it, other components are not available (note that the watch component is integrated directly into the gulp without the need for additional watch components)

gulp-mini-css : Compression CSS uses the

gulp-uglify: Compress, confuse JS file with

Gulp-clean: Empty Folder

1 gulp.src (globs) 2   . Pipe (Clean ());

  gulp-clean-css: Compress css file (original gulp-minify-css discard)

1 gulp.src (' Src/css/t1.css ') 2   . Pipe (Cssmin ()) 3   . Pipe (Gulp.dest ("dest/css/"));

  gulp-less: Compiling less files into CSS

1 gulp.src (' src/css/t.less ') 2   . Pipe (Less ()) 3   . Pipe (Gulp.dest ("dest/css/"))

  gulp-notify: Add console description

1 gulp.src ("./src/test.ext") 2   . Pipe (Notify ("Found file: <%= file.relative%>!"));

  gulp-autoprefixer: Automatically add browser-compatible prefixes to CSS styles

1 gulp.src (' Src/css/t1.css ') 2         . Pipe (Autoprefixer ({3             browsers: [' last 2 versions ', ' Android >= 4.0 '],4             Cascade:true,//whether to beautify the property value default: True like this: 5             //-webkit-transform:rotate (45deg); 6             //        transform:rotate (45DEG); 7             remove:true//whether to remove unnecessary prefixes by default: True 8         }) 9         . Pipe (Gulp.dest (' dist/css '));

  gulp-template://Replace variable and Dynamic HTML

  src/greeting.html

  gulpfile.js处理

1 gulp.src (' src/greeting.html ') 2   . Pipe (Template ({name: ' Sindre '})) 3   . Pipe (Gulp.dest (' dist '))

  gulp-rename://change Name

1 gulp.src (' Src/css/**/*.css ') 2   . Pipe (concat (' All.css ')) 3   . Pipe (Gulp.dest (' dest/css/')) 4   . PIPE ( Rename ({suffix: '. Min '})//Add suffix 5   . Pipe (Gulp.dest (' dest/css '));

  gulp-if: Logical Judgment

1 gulp.task (' Cssmin ', function () {2   gulp.src (' Src/css/**/*.css ') 3     . Pipe (concat (' All.css ')) 4     . PIPE ( Cssmin ()) 5     . Pipe (Gulp.dest (' dest/css ')); 6}); 7 Gulp.task (' Main ', function () {8   gulp.src (' src/css/**/*.css ') 9     . PIPE (GIF (true,cssmin ()))     . PIPE ( Gulp.dest (' dest/css ')); 11});

  del: delete the specified file

Del (' Dest/css/**/*.css ')

  gulp-htmlmin: Compressing HTML

1 gulp.src (' src/html/*.html ') 2   . Pipe (Htmlmin ()) 3   . Pipe (Gulp.dest (' dist/html '));

  gulp-jshint : Check JS

1 gulp.src (' Src/js/*.js ') 2   . Pipe (Jshint ());

  Browser-sync: This is not really a gulp plug-in, but he realized when the file is modified to update the Web page in real-time function, it is interesting, interested in children's shoes can study

  gulp-connect: Starts a Web Server locally. In general, writing the front-end interface code when you want to debug requires a server, this server solves the problem of the previous back-end server.

1 var gulp = require (' Gulp '), 2   connect = require (' Gulp-connect '); 3  4 gulp.task (' Connect ', function () {5   Connect.server (); 6}); 7  8 gulp.task (' Default ', [' Connect ']);

For more details, refer to Https://www.npmjs.com/package/gulp-connect

Use the example to build a local development Web server using Gulp

5. Summary

  from the speed:Gulp is faster than grunt, gulp do not have to read and write files repeatedly. Especially for large projects, using Gulp packaging is really a better choice.

  from the use of simplicity:Grunt required configuration files, in some cases the configuration file will be many, and gulp is broken down by the task, all the configuration into a series of tasks, from the code above may be more concise than grunt.

  from the study cost: Others said gulp study cost is lower than grunt, but in my case, actually both are easy to use, the foundation is very simple, more detailed needs to check the official website, so should be similar.

  from the maturity point:grunt than gulp mature, grunt plug-ins Although some private writing led to the mixed, but the number and completeness than gulp, and even a lot of quirks of the need to find the relevant plug-ins. and generally the more concise things are not suitable for large projects, gulp waiting for inspection. Therefore, it is recommended to use mature grunt for large projects.

Now, the Gulp function is relatively complete, the basic construction is not a problem, so for small and medium-sized projects, according to do programmers must use the best tool standards, compared to recommend gulp.

Gulp because it is a stream-based build, and this flow is vinyl stream, and buffer incompatible, refer to this article http://sentsin.com/web/210.html

Some tips for gulp reference http://www.gulpjs.com.cn/docs/recipes/

If you feel this article is good, please click on the bottom right "recommended"!

Category: Nodejs

Gulp Quick Start

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.