Node.js-based JavaScript project building Tools Gulp Tutorial _javascript Tips

Source: Internet
Author: User
Tags glob
NPM Install Gulp--save-dev 

What is Gulp?
Gulp is a new generation of front-end project building tools, you can use Gulp and its plug-ins to your project code (LESS,SASS) to compile, you can compress your JS and CSS code, or even compress your pictures, gulp only a small number of APIs, so it is very easy to learn. Gulp uses the stream method to process content. Node spawned a batch of automation tools, like Bower,yeoman,grunt.

Similarities and differences of gulp and grunt
easy to use: code is superior to Configuration policy, Gulp allows simple things to continue to be simple, and complex tasks become manageable.
Efficient: Build can be done faster by leveraging Node.js's powerful stream without having to write intermediate files to disk.
High quality: Gulp strict plug-in guidelines to ensure that plug-ins are simple and work the way you want them to.
Easy to learn: by minimizing the API, you can learn to gulp in a very short time. Build your work as you would imagine: a series of streaming pipelines.
Because Gulp is written in node.js, you need to install NPM on your terminal. NPM is the Node.js Package Manager, so install the Node.js on your machine first.

Gulp installation Command

sudo npm install-g Gulp

Create a new Package.json file in the root directory

NPM init.

Install Gulp Package

Once installed, enter gulp-v again to view the version number, as shown in the following illustration for success:

Installing Plug-ins
Install common plugins:

Compilation of sass (Gulp-ruby-sass)
Automatically add CSS prefix (gulp-autoprefixer)
Compress css (GULP-MINIFY-CSS)
JS Code checksum (gulp-jshint)
Merge js file (Gulp-concat)
Compressed JS code (GULP-UGLIFY)
Compress picture (gulp-imagemin)
Automatically refresh page (gulp-livereload)
Picture caching, only the picture is replaced only compressed (Gulp-cache)
Change Reminder (gulp-notify)
Purge Files (del)
Installing these plug-ins requires that you run the following command:

Copy Code code as follows:

$ npm Install gulp-ruby-sass gulp-autoprefixer gulp-minify-css gulp-jshint gulp-concat gulp-uglify Gulp-notify gulp-rename gulp-livereload gulp-cache del--save-dev


-save and-save-dev can save you the steps to manually modify Package.json files.

NPM Install Module-name-save

Automatically add modules and version numbers to the Dependencies section

 
 

Automatically add modules and version numbers to the Devdependencies section
Gulp Command
you just need to know the 5 gulp commands

Gulp.task (name[, Deps], fn) define Task Name: task names Deps: Dependent Task name fn: callback function

Gulp.run (Tasks ...) : Run as many tasks as possible in parallel

Gulp.watch (Glob, fn): When glob content changes, execute FN

GULP.SRC (glob): The path to a file that needs to be processed can be multiple files in the form of an array, or it can be a regular

Gulp.dest (path[, Options]): Setting the path of the build file
Glob: Can be a direct file path. His meaning is pattern matching.
Gulp the file to be processed through the pipeline (pipe ()) API to guide the relevant plug-ins. Perform a file processing task through a plug-in.

Gulp.task (' Default ', function () {...});

Gulp.task This API is used to create tasks, at the command line you can enter $ gulp [default], which is optional in brackets, to perform the above tasks.

Gulp Official API Documentation: HTTPS://GITHUB.COM/GULPJS/GULP/BLOB/MASTER/DOCS/API.MD

Gulp Plug-in Daquan: http://gulpjs.com/plugins/
Start building projects
Create a new Gulpfile.js file under the project root and paste the following code:

Introducing Gulp and Uglify Plug-ins in the project root directory
var gulp = require (' gulp ');
var uglify = require (' gulp-uglify ');

Gulp.task (' Compress ', function () {return
  gulp.src (' script/*.js ')
  . Pipe (Uglify ()). Pipe (Gulp.dest (
  ' Dist '));


Note: The Gulpfile.js file name cannot be changed.
The project needs to use the Uglify and rename Plug-ins to install the following command:

NPM Install--save-dev gulp-uglify
npm Install--save-dev gulp-rename

Take my example, enter the directory where Gulpfile.js is located:

Cd/users/trigkit4/gulp-test

Then enter:

var gulp = require (' gulp ');
var uglify = require (' gulp-uglify ');
var rename = require (' Gulp-rename ');

Gulp.task (' Compress ', function () {return
  gulp.src (' script/*.js ')
  . Pipe (Uglify ()). Pipe (Rename (
  ' Jquery.ui.min.js '))
  . Pipe (Gulp.dest (' dist '));


This command installs all the dependencies under Package.json, as shown in the following illustration:

The Complete gulpfile.js

Load plug-in var gulp = require (' Gulp '), sass = require (' Gulp-ruby-sass '), Autoprefixer = require (' Gulp-autoprefixer '), Minifycss = require (' Gulp-minify-css '), Jshint = require (' Gulp-jshint '), uglify = require (' gulp-uglify '), imagemin = Require (' gulp-imagemin '), rename = require (' gulp-rename '), clean = require (' Gulp-clean '), concat = require (' Gulp-c
 
Oncat '), notify = require (' gulp-notify '), cache = require (' Gulp-cache '), Livereload = require (' gulp-livereload ');
  Style gulp.task (' Styles ', function () {return gulp.src (' src/styles/main.scss '). Pipe (Sass ({style: ' expanded ',}) . Pipe (Autoprefixer (' last 2 version ', ' Safari 5 ', ' IE 8 ', ' IE 9 ', ' Opera 12.1 ', ' iOS 6 ', ' Android 4 '). Pipe (Gulp.dest (' d Ist/styles ')). Pipe (rename ({suffix: '. Min '})). Pipe (Minifycss ()). Pipe (Gulp.dest (' Dist/styles ')). Pipe (Notify ({
Message: ' Styles task Complete '});
 
}); Script Gulp.task (' Scripts ', function () {return gulp.src (' src/scripts/**/*.js '). Pipe (Jshint ('. JshintRC ')). Pipe (Jshint.reporter (' Default ')). Pipe (Concat (' main.js ')). Pipe (Gulp.dest (' dist/scripts ')). Pipe (rename ({s Uffix: '. Min '}). Pipe (Uglify ()). Pipe (Gulp.dest (' dist/scripts ')). Pipe (notify ({message: ' Scripts task complete '}
));
 
});  Picture Gulp.task (' images ', function () {return gulp.src (' src/images/**/* '). Pipe (Cache imagemin ({optimizationlevel:3, Progressive:true, Interlaced:true})). Pipe (Gulp.dest (' dist/images ')). Pipe (notify ({message: ' Images task complet
E '}));
 
}); Cleans up gulp.task (' Clean ', function () {return gulp.src ([' Dist/styles ', ' dist/scripts ', ' dist/images '], {read:false}).
Pipe (clean ());
 
});
 
Preset task Gulp.task (' Default ', [' clean '], function () {gulp.start (' styles ', ' scripts ', ' images ');});
 
 Guard Gulp.task (' Watch ', function () {//detention center has. scss file Gulp.watch (' Src/styles/**/*.scss ', [' Styles ']);
 
 The detention center has. js file Gulp.watch (' Src/scripts/**/*.js ', [' Scripts ']);
 
 The detention center has picture file Gulp.watch (' src/images/**/* ', [' images ']); Establishment of an instant reformer servoConverter var server = Livereload ();
 The detention center has a file in the dist/directory and, if any changes are made, it is restructured gulp.watch ([' dist/** ']). On (' Change ', function (file) {server.changed (File.path);
 
});
 });

Note: pipe () is a stream module transfer data flow of a method, the first parameter is the plug-in method, the plug-in will receive the file from the upstream, processing processing, and then downward flow.

Gulp.task (' Task Name ', function () {return
  gulp.src (' File path ')
    . Pipe (...).
    Pipe (...)
    Until the last step of the task
    . pipe (...);
};


Gulp Plugin
gulp-gh-pages: Use Gulp to generate HTML documents for Markdown and upload them to git pages
Https://github.com/shinnn/gulp-gh-pages

var gulp = require (' gulp ');

var ghpages = require (' gulp-gh-pages ');



Gulp.task (' Deploy ', function () {return

 gulp.src ('./dist/**/* ')

  . Pipe (Ghpages ());

};


Gulp-jade plugins: Compiling jade into HTML files
Gulp-less plugins: Compiling less into CSS files

 var less = require (' gulp-less ');

 

var path = require (' path '); Gulp.task (' Less ', function () {return gulp.src ('./less/**/*.less '). Pipe (Less ({paths: [Path.join (__dirname, ' l

ESS ', ' includes ')]). Pipe (Gulp.dest ('./public/css '));
});

 Gulp-live-server plugin: Handy, lightweight server var gulp = require (' gulp ');

 var GLS = require (' Gulp-live-server '); Gulp.task (' Serve ', function () {//1. Serve with default settings var server = Gls.static ();//equals to Gls.static (' Pu

 Blic ', 3000);



 Server.start (); 2.

 Serve at custom port var server = gls.static (' dist ', 8888);



 Server.start (); 3.

 Serve multi folders var server = gls.static ([' Dist ', '. tmp ']);



 Server.start (); Use Gulp.watch to trigger server actions (notify, start or stop) gulp.watch ([' Static/**/*.css ', ' static/**/*.html '], Fu

 Nction (file) {server.notify.apply (server, [file]);

});

}); 

Gulp-livereload, you can save the refresh in real time, so you don't have to press F5 and switch interfaces.
Gulp-load-plugins: Automatically load any gulp plugins in your Package.json file

$ NPM Install--save-dev Gulp-load-plugins

For example, a given Package.json file is as follows:

{"

  dependencies": {"

    gulp-jshint": "*",

    "Gulp-concat": "*"

  }

}

Add the following code to the Gulpfile.js:

var gulp = require (' gulp ');

var gulploadplugins = require (' Gulp-load-plugins ');

var plugins = Gulploadplugins ();
Plugins.jshint = require (' Gulp-jshint ');

Plugins.concat = require (' Gulp-concat ');

Gulp-babel:gulp's Babel plugin,

$ npm Install--save-dev Gulp-babel babel-preset-es2015

How to use:

Const GULP = require (' gulp ');
Const BABEL = require (' Gulp-babel ');

Gulp.task (' Default ', () => {return
  gulp.src (' src/app.js ')
    . Pipe (Babel ({
      presets: [' es2015 ']
    })
    . Pipe (Gulp.dest (' dist ');
});

Official Github:https://github.com/gulpjs/gulp

Related Article

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.