Front-end build tool Gulp Getting Started tutorial

Source: Internet
Author: User
Tags install node

This article assumes that you have not previously used any task scripts (task runner) and command-line tools, step by step to teach you to get started gulp. Do not be afraid, it is actually very simple, I will be divided into five steps to introduce you to gulp and help you accomplish some amazing things. Let's go straight to the beginning.

First Step: Install node

First of all, the most basic and most important thing is that we need to build the node environment. Visit http://nodejs.org, then click the Big Green install button and run the program directly after the download is complete, and everything is ready. NPM will be installed with the installation package and will be used later.

Step two: Use the command line

Maybe now you don't quite understand what a command line--osx in the terminal (Terminal), in Windows command Prompt, but soon you'll know. It doesn't look that simple, but once you get the hang of it, it's easy to execute a lot of command-line programs, such as Sass,yeoman and Git, which are very useful tools.

If you are familiar with the command line, skip directly to step four.

To make sure that node is properly installed, we execute a few simple commands.

node -v

Enter (enter), if installed correctly, you will see the version number of the node installed, and then see NPM.

npm -v

This will also get the NPM version number.

If these two lines of command are not returned, the node may not be installed correctly, try restarting the command-line tool, and if not, you can only go back to the first step to reload.

Step three: Navigate to the project

Now that we have an overview of the command line and know how to use it simply, the next two simple commands can be used to locate the file directory and see what files are in the directory.

    1. CD, navigate to Directory
    2. LS, listing the file list

It is recommended to tap these two commands to learn more about the file system and to know where the files are.

Accustomed to using these two commands, it is necessary to enter our project directory, this directory is different, for example, this is my command to enter the project directory:

cd /Applications/XAMPP/xamppfiles/htdocs/my-project

After successfully entering the project directory, we started to install Gulp.

Fourth Step: Install Gulp

We already know how to use the command line, now try something new, know NPM and then install Gulp.

NPM is a command-line-based node package management tool that installs node's program module into a project and can view and search all available program modules on its website.

sudo npm install -g gulp 
    1. sudo executes the command as an administrator and typically requires a computer password
    2. NPM is the tool for installing the node module, executing the install command

    3. -G means installed in the global environment so that any project can use it

    4. Finally, Gulp is the name of the node module that will be installed

While the runtime is aware that there is no error message on the command line, you can use the following command to view the Gulp version number to ensure that Gulp is installed correctly.

gulp -v

Next, we need to install the Gulp to the project local

npm install —-save-dev gulp

Here, we use —-save-dev to update the Package.json file, updating the devDependencies value to indicate that the project needs to rely on gulp.

DependenciesYou can indicate to other participants in the project that the node module in the development environment and production environment is lazy and want to know more about it to see the Package.json documentation.

Fifth step: Create a new Gulpfile file and run the Gulp

After installing gulp we need to tell it what to do for us, first of all we need to figure out what tasks the project needs.

    • Check JavaScript
    • Compiling sass (or less) files
    • Merging JavaScript
    • Compress and rename merged JavaScript
Installation dependencies
npm install gulp-jshint gulp-sass gulp-concat gulp-uglify gulp-rename --save-dev 

Note that if the above command prompts for permission errors, you need to add the sudo attempt again.

New Gulpfile File

Now that the components are installed, we need to create a new Gulpfile file to specify what the gulp needs to accomplish for us.

Gulp has only five methods:,,, task run watch src , and dest , in the project root, create a new JS file and name it gulpfile.js , and paste the following code in:

Gulpfile.js

Introduction of Gulpvar gulp =Require' Gulp ');Introducing Componentsvar jshint =Require' Gulp-jshint ');var sass =Require' Gulp-sass ');var concat =Require' Gulp-concat ');var uglify =Require' Gulp-uglify ');var rename =Require' Gulp-rename ');Check Script Gulp.task (' Lint ', function () {GULP.SRC ('./js/*.js '). Pipe (Jshint ()). Pipe (Jshint.reporter (' Default ');});Compile Sassgulp.task (' Sass ', function () {GULP.SRC ('./scss/*.scss '). Pipe (Sass ()). Pipe (Gulp.dest ('./css ');}); //merge, compress file Gulp.task (' scripts ', function () {gulp.src ('./js/*.js '). Pipe (Concat (' all.js ')). PIPE ( Gulp.dest ('./dist ')). Pipe (Rename (' All.min.js ')). Pipe (uglify ()). Pipe (Gulp.dest ('./dist '));}); //Default task Gulp.task (' Default ', function () {Gulp.run (' lint ', ' sass ', ' scripts '); //Listening file changes Gulp.watch ('./js/*.js ', function () {Gulp.run (' lint ', ' sass ', ' scripts ');} ); 

Now, the segment explains the code.

Introducing Components
var gulp = require(‘gulp‘); var jshint = require(‘gulp-jshint‘);var sass = require(‘gulp-sass‘);var concat = require(‘gulp-concat‘);var uglify = require(‘gulp-uglify‘);var rename = require(‘gulp-rename‘);

In this step, we introduced the core gulp and other dependent components, and next, create the four different tasks of lint, sass, scripts, and default separately.

Lint Tasks
gulp.task(‘lint‘, function() {    gulp.src(‘./js/*.js‘)        .pipe(jshint())        .pipe(jshint.reporter(‘default‘));});

The link task checks js/ whether the JS file in the directory has an error or warning.

Sass Tasks
gulp.task(‘sass‘, function() {    gulp.src(‘./scss/*.scss‘)        .pipe(sass())        .pipe(gulp.dest(‘./css‘));});

The SASS task compiles the scss/ scss file in the directory and saves the compiled CSS file to the /css directory.

Scripts Tasks
gulp.task(‘scripts‘, function() {    gulp.src(‘./js/*.js‘)        .pipe(concat(‘all.js‘))        .pipe(gulp.dest(‘./dist‘)) .pipe(rename(‘all.min.js‘)) .pipe(uglify()) .pipe(gulp.dest(‘./dist‘));});

The scripts task merges js/ all the JS files in the directory and outputs them to the dist/ directory, and then gulp renames, compresses the merged files, and outputs them to the dist/ directory.

Default task
gulp.task(‘default‘, function(){    gulp.run(‘lint‘, ‘sass‘, ‘scripts‘); gulp.watch(‘./js/*.js‘, function(){ gulp.run(‘lint‘, ‘sass‘, ‘scripts‘); });});

At this point, we create a default task that is based on other tasks. Use .run() methods to correlate and run the tasks defined above, use the .watch() method to listen for file changes in the specified directory, and, when there are changes to the file, run other tasks defined by the callback.

Now, back to the command line, you can run the Gulp task directly.

gulp

This will perform the defined default task, in other words, the same meaning as the following command

default

Of course, we can run any task defined in Gulpfile.js, for example, now running the SASS task:

gulp sass

(Kimi: Wow, cool than ah ~)

Conclusion

Now that you've done that, set up the gulp task and run them, and now look back to the previous study.

    1. Learn to install the node environment
    2. Learn the simple use of the command line
    3. Learned to use the command line to enter the project directory
    4. Learned to use NPM and install Gulp
    5. Learn how to run a gulp task
What is Gulp

The official definition of Gulp is very concise: a file-stream-based build system. The main differences between streaming, gulp and grunt in the construction process are highlighted here. The specific difference is where, the following will be introduced briefly.

The streaming build system.

Another grunt?

Believe that a lot of front-end classmates to grunt are not unfamiliar, grunt appearance can be said to be the front-end of the gospel, a lot of people need to complete the repetitive work, with the grunt, a command to get it done.

Speaking of which, many students may be more doubtful: Since the grunt, the same positioning in the front-end of the construction of the gulp the significance of the existence? From the introduction of Gulp, Gulp is to solve the front-end students in the use of the grunt process encountered such problems and appear. What are the problems? In the slide of Http://slid.es/contra/gulp, several points were mentioned, such as:

Some problems existed in grunt

1, plug-in function is not single

2, the plug-in completed this should not be done by the plug-in things (this I am a little confused, why is things don ' t need to be plugins? )

3, the configuration is too complex

4. Temporary files/directories due to poor process control

    • Plugins do multiple Things
      • Want a banner? Use the JavaScript minifier
    • Plugins do things that don ' t need to be Plugins
    • Grunt config format is a mess this tries to do everything
    • Headache of temp files/folders due to bad flow control
Built in a grunt way

The previous list of four points grunt the use of the problem, of which 1, 2 points of personal feel slightly far-fetched, plug-in function is not single, or complete should not be done by the plug-in things, this with grunt in fact, the relationship is not big, More should be attributed to the author of the plugin (the author of the most frequently used part of the plugin is the brother of the grunt team).

The next two points are more agreeable: complex configuration, poor process control.

The complexity of the configuration is not too much to say, and in this regard it may be a big fight for Parliament. Poor process Control is criticized more, especially in larger projects. The following diagram is Grunt's current workflow: Read files, modify files, write files-read files, modify files, write files ——。。。

The problem is obvious:

1, inefficient: Frequent disk IO will make the construction efficiency become low

2, not effective concatenation : Read files, modify files, write the loop of the file, resulting in plug-ins and plug-ins before the work can not effectively series together.

Note: The drawing comes from the slide mentioned above

As an example,

For example, under the project there is a index.html, App.scss, App.js, and Index.html quoted App.css, App.js, as shown below. Assuming the final goal is to compile the compressed app.css, compressed app.js inline into the index.html, while preserving the pre-compression app.css, app.js source files, then the process may be as follows: (not necessarily completely accurate)

1, copy the index.html, app.js, compile generated app.css to dist/

2. Compress app.js, app.css, and generate to temp directory. tmp/

3, the. tmp/app.js,. Tmp/app.css in the dist/index.html

<html><head><type=rel=href="app.css"/></Head ><body><src="App.js" ></script></body> </html>                
Built in a gulp way

As you can see from the build process above, multiple file reads and writes, as well as temporary directories, appear in an unavoidable gesture. In the Gulp author's conception, the reasonable construction process should be this: read the file--Modify the file--Modify the file ... --Write a file (map from the slide mentioned above)

In this scenario, the example above is rewritten with gulp, and the process should be

1, read the file: Read index.html, App.js, app.css (read file)

2, compile, compress app.css, compress app.js (process file stream)

3, the A, B inline into the index.html (or processing file streams)

4. write the file : Write the result of the final generation to the dist/directory (modified index.html, compiled app.css, unmodified app.js)

A simple example of compressing a file

1, first global Installation Gulp command line tool (equivalent to GRUNT-CLI)

NPM Install-g Gulp

2, then, under the Project Installation Gulp (equivalent to grunt), gulp-uglify

--save-dev Gulp Gulp-uglify

3. Create gulpfile.js under the project root directory

Require (' gulp '),    require ('gulp-uglify '); Gulp.task (' Default ', function () {    gulp.src (' Src/app.js '). pipe (Uglify ()). Pipe (Gulp.dest (' dist/');});       

4. Running Gulp

Gulp
See what's different

As you can see from the example above, gulp seems to be a bit like grunt (also a command-line tool combined with a local build tool), but the difference is obvious. Grunt is all based on configuration (configuration-as-a-task), while gulp is code based workflow (in fact, it's a bunch of configurations, but significantly more readable). Here is a more detailed introduction, summarized below. One of the more important is the second and 5th. The 5th has already been told.

On the 2nd, the personal understanding is that when we use the Gulp plug-in, we only need to understand the plug-in itself depends on the original configuration of the library, and not like grunt, often is the configuration wrapper layer after the exposure to users, such as Grunt-contrib-compass. While it may be possible to make the configuration of the plug-in more uniform, it does result in additional understanding costs.

    • With Gulp your build file was code, not config
    • Libraries to do things
    • Plugins is simple and do one thing-most is a line function
    • Tasks is executed with maximum concurrency
    • I/O works the IT
Write it in the back.

Although gulp the banner of replacing Grunt, it is still necessary to look at the problem objectively. The tool itself has its own scenario, and it may be unrealistic to want a panacea. Gulp relatively young, but also need more testing, but the individual is very optimistic. In addition to grunt, gulp, Baidu's FIS is also quite good, wall crack recommended.

For more gulp content, welcome to Dabigatran discussion 372015911

Some links:

Gulp's GitHub Address: Https://github.com/gulpjs/gulp

Gulp,the Streaming Build System:http://slid.es/contra/gulp

FIS Official website: http://fis.baidu.com/

Front-end build tool Gulp Getting Started tutorial

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.