Gulp First Experience record

Source: Internet
Author: User

  At present, the industry is more well-known three front-end building tools: Grunt, Gulp, FIS, I have been only in the past with Grunt,fis have seen a little, gulp has not been noticed, until recently found it seems to use more and more people, so today also smoked a bit of time to try a bit.

"What is Gulp?"

The official word is: Gulp is a stream-based, code-better next-generation build tool than configuration.

It can be said that gulp and grunt a bit similar, but from the writing point of view, write Grunt Gruntfile is to write a configuration file, relatively cumbersome and initially the semantics are not very clear, and write Gulp Gulpfile is equivalent to writing code. Coupled with a streaming solution, so that its configuration file code structure clearer, from this point on which better actually also a matter of opinion, at least I used the gulp after this configuration to feel more appropriate for their own, will also be in later projects to try to replace Grunt.

From the concrete construction of gulp and grunt, each plug-in call of Grunt is a new IO operation, namely:

Start construction = Read File + plug-in change file = Write File = Read File = Plugin change file = Write file = build complete

When the project is large enough, a large number of IO operations can make the entire build process extremely inefficient. The gulp uses a more efficient construction idea, which is to use the flow to concatenate the construction of each plug-in, forming the following:

Start Build = Read file + plugin change file = Plugin Change file = Write file = build complete

The increase in efficiency is obvious.

"The use of Gulp"

The use of gulp and its simple, because the online information is very much, so here but more than repeat, with a simple example to summarize can

1. Install Gulp Command line tool: NPM Install-g Gulp

Create the test directory, open the test directory, create a new Test1.js file and create a new Test2.js file

2. Installing GULP:NPM install--save-dev Gulp in test directory

3. Install Concat tool: NPM Install Gulp-concat

4. Create Gulpfile and write the following content

var gulp = require ("gulp"); var concat = require ("Gulp-concat") gulp.task(function() {    Console.log (" Gulp is running ")    return gulp.src ([" Test1.js "," Test2.js "])            . Pipe (Concat (" Result.js "))            . Pipe (Gulp.dest ("./build/"))})

  5, open the command line Input gulp, hit enter, found in the build directory with a result.js file

Build complete.

For more use, refer to http://www.smashingmagazine.com/2014/06/11/building-with-gulp/

"Gulp plug-in development"

Gulp plug-in development is not grunt so intuitive, grunt words, just register a task, and then you can pass in the Grunt object in the files to get all the file path and output path, and then only need to use the FS module to obtain these files and then processing on the line. But Gulp is a little bit different, from the way it is written in the configuration file can be seen.

The gulp is flow-connected using pipe. There are four streams in the nodejs, including readable readable streams, writable writable streams, duplex duplex streams, and transform conversion streams. the specific explanations of these four streams can be seen in the official documentation:http://nodeapi.ucdok.com/#/api/stream.html

Analyze the code for the above configuration file: Gulp.src (["Test1.js", "Test2.js"]). Pipe (Concat ("Result.js")). Pipe (Gulp.dest ("./build/")), where GULP.SRC (["Test1.js", "Test2.js"]) is the acquisition of a file stream, which is a readable stream, which needs to be processed after the file stream has been obtained, it is entered into the concat ("Result.js") through the pipe method and processed, After processing also need to transfer to the next link, that is, concat ("Result.js") this method after the completion of the return content must be a conversion stream object, because the conversion stream object is also duplex, readable can also be written. After processing, the pipe (Gulp.dest ("./build/") is executed and written out. In Sketch's case:

  

  In other words, the middle transform is actually the plugin we want to implement, and our plugin needs to return a transform stream object.

Knowing this, we can start our own plug-in development. Build the file first, and then write the following code

 var fs = require ("FS")var gulputil = require ("Gulp-util")var stream = Require (' stream 'function() {    var  transform;    return  transform;}

  This piece has not realized any content, if Gulp directly quoted also certainly is error, first not urgent, step by step, above Gulp-util is Gulp provides a tool module, the following method body, first put the value to return to write well, we want to return a transform stream object, so, We have to instantiate a transform stream object first.

The above is also changed to: var transform = new stream. Transform ({objectmode:true});

Where the Objectmode parameter must have, as the name implies: Object mode, only with this parameter, transform is an implementation-oriented conversion stream object, or a consumer-oriented heap of buffer block

The transform Stream object has, how do we get the file stream, and how to deal with it? A description of a method in the conversion flow is found through the official document of Nodejs:

  

  In other words, we need to implement a _transform method for the instantiated stream object, and when the data is passed in, it is called and the relevant parameters are passed in. So add a piece of code:

 var file; 
Transform._transform = function (Chunk, Encoding, callback) {Console.log (chunk.contents) // Here output the incoming file stream, which is a buffer
file = chunk; // var str = chunk.contents.toString (); // For example str here is "Hello ${arg}" str = str.replace (' ${arg} ', ' Gulp ' ) chunk.contents = new Buffer (str) this .push (Chunk) callback (); }

in other words, the processing of the contents of the file is handled here. After processing, push through This.push (chunk) into the transform stream object, and then call the callback instructions to complete the execution. And then we can implement a method _flush

function (CB) {        // change file output name        File.path = file.path.substring (0, file.path.lastIndexOf ("\ \") )) + "\\newfile.js";          This . push (file)        CB ()    }

  This method will be executed at the time of the stream output, for example, if we want to change the file name, we can save the chunk in the previous _transform method, and then execute _flush to change the file name and then push the transform stream object through This.push (). The execution of the callback ends again.

Basically the entire plug-in development of the shelf is this, is to deal with streaming data.

One problem, though, is the stream. Transform is in the Nodejs v0.10 version only, so the current gulp mainstream plug-in, most to be compatible with the previous version, the implementation of the conversion stream with the third-party tools, such as THROUGH2. But the wording is similar:

varfilevarTransform = Through2.obj (function(chunk, encoding, callback) {Console.log (chunk.contents)//output the incoming file stream here, which is a bufferfile=Chunk; //file stream content can be processed here        varstr = chunk.contents.toString ();//For example, here str is "Hello ${arg}"str = str.replace (' ${arg} ', ' Gulp ') chunk.contents=NewBuffer (str) This. Push (chunk) callback (); },function(CB) {File.path= file.path.substring (0, file.path.lastIndexOf ("\ \")) + "\\newfile.js";  This. Push (file) CB ()}) returnTransform

Gulp First Experience record

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.