Gulp.js Introduction

Source: Internet
Author: User
Tags install node css preprocessor

Gulp.js Introduction

We discussed a lot about how to reduce the volume of pages and improve the performance of heavy sites. Some are operations that are once and for all, such as turning on the server's gzip compression, using the appropriate image format, or removing some unnecessary characters. But there are some tasks that must be repeated every time you work. Such as

    • Compression of new or modified images
    • Remove debug statements such as Console,debugger
    • Merging and compressing CSS and JS
    • Deploy the updated files to the server

You may assume that everyone remembers all of these operations, but there will always be people who forget one or two. As the project gets bigger and larger, the work above is wasting time. Have to set up someone to complete these boring work.

Can you let these jobs not occupy the hands?

You need an automated running program or build process, which sounds complicated.

While building this build process is much more complex than performing each small task individually, you can save a lot of time and effort as the application grows, and you can avoid mistakes.

take a pragmatic approach:

    • Automate the most time-consuming tasks
    • Do not over-design, initial installation settings as short as possible and simple
    • Use a task management tool for a while, don't switch to another one on the spur of the moment.

We will discuss some new tools and concepts.

    1. node.js-We're going to use node. js, but don't know it too deep, just know some javascript knowledge and use a search engine as well.
    2. Command line-you will have to enter commands, although there is no graphical interface, but some commands are simple.
Grunt vs Gulp

You may have heard that Grunt,grunt is a build tool based on node. js

Gulp is a new build tool based on node. js

Grunt and gulp do the same thing. Grunt come out earlier, development is also good, can find a lot of plugins and resources, and can find a lot of tutorials. This is a very good tool, if you are already familiar with the tool, what problems will let you replace it?

Without the perfect tool, Gulp.js was developed to solve some problems that grunt cannot solve:

    • Grunt plug-ins often perform multiple tasks, gulp plugins only do one thing
    • Grunt need plug-ins to complete some basic functions, such as file monitoring, gulp built-in basic functions
    • Grunt uses a JSON-formatted configuration file, and Gulp uses a leaner, simpler JS code to configure

Not everyone feels the last one, gulp is better than grunt, but it is recommended to check out the Gulp presentation slide and judge for yourself.

The most important thing is that gulp is a flow-based concept. Think about it, your file passes through a pipe that is executed on one or more points along that pipe. (much like assembly line)

For example, we can put all of our JS files into a script pipeline, where

    1. Merge into one file
    2. Remove Debug Code
    3. Compress code
    4. Place the generated file in the specified directory

Data input into a method. The new data that the method outputs is used by the next method. This makes you feel like a chained invocation of jquery, such as

$("#element").text("hello world!").addClass("myclass").fadeIn();

The theory is finished, the following hands Use Gulp bar.

1th Step: Install node. js

can go to the official website to download the corresponding version of your computer system, specifically how to install their own Baidu it.

When the installation is complete, open the command line and enter

node -v

Displays the node version you are currently installing. The following can also be entered

npm -v

View version information for the Package Manager for node. js.

If any of the commands fail, check to see if you have entered the command incorrectly. If that's true, that's better, it means your node installation is successful.

2nd Step: Install Gulp

Using NPM to install Gulp, you need to add the-G flag to install the gulp into the global environment, so that it can be used in any project.

npm install gulp -g

If you are using Mac or Linux, you need to add sudo to the command before you switch to Administrator privileges.

sudo npm install gulp -g

Enter the following command to see if the Gulp is installed successfully

gulp -v
3rd Step: Configure the Project

For example, if your project folder is test, switch to the project folder first

cd test

Depending on the system, window can use the Dir,mac/linus to view the file directory with LS

Our test folder, including the following sub-folders

    • src -the location of pre-processed HTML source files and folders:
      • Images -uncompressed Images
      • Scripts -multiple pre-processed script files
      • styles -multiple pre-processed CSS files
    • Build -the location of production files for upload including:
      • Images -compressed Images
      • Scripts -a single minified script file
      • Styles -a single minified CSS file

(The build folder is our build directory, which is generated by an automated task)

First, install Gulp in the project.

npm install gulp --save-dev

This command creates a Node_modules folder in test that holds the gulp and its plugins.

Finally, create an empty gulpfile.js configuration file in the Test folder. Here are the tasks we want to declare.

4th step: Install the 1th Gulp plugin

Gulp cannot work on its own, you must install and configure plugins to perform specific tasks. First install Jshint, to detect the quality of our JS source files. The installation commands are as follows

npm install gulp-jshint --save-dev

Open the Gulpfile.js file and add the following code

// include gulpvar gulp = require(‘gulp‘); // include plug-insvar jshint = require(‘gulp-jshint‘);// JS hint taskgulp.task(‘jshint‘, function() {  gulp.src(‘./src/scripts/*.js‘)    .pipe(jshint())    .pipe(jshint.reporter(‘default‘));});

The meaning of the above code is.

    1. Reference Gulp
    2. Put the Gulp-jshint plug-in object into the Jshint variable
    3. Declares a new Gulp task Jshint. This puts all the JS files inside the src/scripts into the Jshint object, and outputs the errors found to the console.

Save the Gulpfile.js file and run the task at the command line as follows

gulp jshint

You will get the following information in the console:

[gulp] Using file D:\test\gulpfile.js[gulp] Working directory changed to D:\test[gulp] Running ‘jshint‘...[gulp] Finished ‘jshint‘ in 8.24 msD:\test\src\scripts\lib.js: line 2, col 20, Missing semicolon.1 error
5th step: Add Other tasks

Let's try some more plugins. We will look for new images or modify images under the Src/images folder, compress them and export them to the Build/images folder. To do this, we need to install the gulp-changed and gulp-imagemin two plugins.

npm install gulp-changed --save-devnpm install gulp-imagemin --save-dev

They are then referenced in the Gulpfile.js file.

var changed = require(‘gulp-changed‘);var imagemin = require(‘gulp-imagemin‘);

and add a new Gulp task to execute the plugin

// minify new imagesgulp.task(‘imagemin‘, function() {  var imgSrc = ‘./src/images/**/*‘,      imgDst = ‘./build/images‘;  gulp.src(imgSrc)    .pipe(changed(imgDst))    .pipe(imagemin())    .pipe(gulp.dest(imgDst));});

Save the Gulpfile.js, and then run the following command at the command line

gulp imagemin

The image is compressed and saved to the corresponding folder in the build directory, and the following information is available in the console

[gulp] Using file D:\test\gulpfile.js[gulp] Working directory changed to D:\test[gulp] Running ‘imagemin‘...[gulp] Finished ‘imagemin‘ in 5.71 ms[gulp] gulp-imagemin: ? battery.png (saved 2.7 kB)[gulp] gulp-imagemin: ? app.png (saved 3.2 kB)[gulp] gulp-imagemin: ? tick.png (saved 2.8 kB)

In the same way, we can add the gulp-minify-html plugin to compress all the HTML files under SRC

npm install gulp-minify-html --save-dev

Modify the Gulpfile.js file to add a new task HtmlPage

// include plug-insvar minifyHTML = require(‘gulp-minify-html‘);// minify new or changed HTML pagesgulp.task(‘htmlpage‘, function() {  var htmlSrc = ‘./src/*.html‘,      htmlDst = ‘./build‘;  gulp.src(htmlSrc)    .pipe(changed(htmlDst))    .pipe(minifyHTML())    .pipe(gulp.dest(htmlDst));});

Save the Gulpfile.js, and then test the HTML compression

gulp htmlpage

Very simple, huh? Below to use the JS-related plug-in, the source files to merge, compress, remove debugging code plug-ins.

or install it first

npm install gulp-concat --save-dev npm install gulp-strip-debug --save-dev npm install gulp-uglify --save-dev

Add a new task to gulpfile.js scripts

// include plug-insvar concat = require(‘gulp-concat‘);var stripDebug = require(‘gulp-strip-debug‘);var uglify = require(‘gulp-uglify‘);// JS concat, strip debugging and minifygulp.task(‘scripts‘, function() {  gulp.src([‘./src/scripts/lib.js‘,‘./src/scripts/*.js‘])    .pipe(concat(‘script.js‘))    .pipe(stripDebug())    .pipe(uglify())    .pipe(gulp.dest(‘./build/scripts/‘));});

In this example, we use an array to pass the value to the Gulp.src method. This allows JS to be merged and compressed in a given order, which solves some dependencies. Save As above, then run the task

gulp scripts

Finally let's deal with CSS files, using add browser prefix plugin, compression plugin.

Installation

npm install gulp-autoprefixer --save-dev npm install gulp-minify-css --save-dev

Update Gulpfile.js file

// include plug-insvar autoprefix = require(‘gulp-autoprefixer‘);var minifyCSS = require(‘gulp-minify-css‘);// CSS concat, auto-prefix and minifygulp.task(‘styles‘, function() {  gulp.src([‘./src/styles/*.css‘])    .pipe(concat(‘styles.css‘))    .pipe(autoprefix(‘last 2 versions‘))    .pipe(minifyCSS())    .pipe(gulp.dest(‘./build/styles/‘));});

Last Run

gulp styles

To the Autoprefixer plugin, passed in as a string or array browser support configuration, here we want to support all the latest two versions of the browser. It will compare each attribute according to the data in caniuse.com, and add the prefix. You can avoid manually querying and adding corresponding prefixes each time.

In these examples we just demonstrate a few useful plugins, you can also go to npmjs.org to find what you need. Some of the other useful plugins are:

    • Gulp-sass a node version of the CSS preprocessor
    • Gulp-clean can be used to remove useless files or folders
    • Gulp-file-include replace the corresponding @ @inclue (' filename ') with the corresponding file
    • Gulp-size size of log files and project files
6th step: Automating Tasks

So far, we've all run one task at a time, and Gulp allows us to perform all of the subtasks it relies on in one task. The following creates a default task in Gulpfile.js

// default gulp taskgulp.task(‘default‘, [‘imagemin‘, ‘htmlpage‘, ‘scripts‘, ‘styles‘], function() {});

Then run the following command at the command line

gulp

All tasks are performed in order.

But it's too much trouble to do it all the time. Gulp can use the Watch method to listen to your folders and, if there is a change, perform a task to complete. Let's modify the default task so that it can listen for changes in the Html,css,js,image file.

// default gulp taskgulp.task(‘default‘, [‘imagemin‘, ‘htmlpage‘, ‘scripts‘, ‘styles‘], function() {  // watch for HTML changes  gulp.watch(‘./src/*.html‘, function() {    gulp.run(‘htmlpage‘);  });  // watch for JS changes  gulp.watch(‘./src/scripts/*.js‘, function() {    gulp.run(‘jshint‘, ‘scripts‘);  });  // watch for CSS changes  gulp.watch(‘./src/styles/*.css‘, function() {    gulp.run(‘styles‘);  });});

Now let's run it again.

gulp

The program will remain active and run when you change the file. You no longer need to run the task every time.

7th Step: Effect

You can reduce the page volume by 50% by using the method above to process the item. When you spend a few hours studying gulp, it is easier to learn than grunt. Hopefully this tutorial will be useful for you, and you'll be able to build your own gulp build tool.

RELATED links:

    • GULP Home Page
    • Gulp Plug-ins
    • node. JS Home Page

Original: An Introduction to Gulp.js

Original link: http://www.sitepoint.com/introduction-gulp-js/

Gulp.js Introduction

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.