Automated front-end build tool--gulp

Source: Internet
Author: User
Tags glob

Gulp is a task-based JavaScript Engineering command-line streaming build tool. Why do you use Gulp? Front-end development into the engineering phase, we need to compress the merged files, add MD5 stamp, if you use COFFEESCRIPT/ES6 to replace Javascript, then need to compile into jacascript, if you use less or sass, you need to compile into CSS. All of these operations, after modifying the file, must be re-executed again, very cumbersome. Gulp is for us to complete this set of repetitive and mechanical work. He can auto-detect files, change every time, automatically compile packaging and so on.

The usage is described below.

Install Gulp first. Create a new folder on the desktop and go to the folder to perform NPM init. The default installation is sufficient. This helps us build a project quickly.

c:\users\admin>cd desktopc:\users\admin\desktop>mkdir gulptestc:\users\admin\desktop> CD gulptestc:\users\admin\desktop\gulptest>NPM Init

Then install the plugins we need in the project catalog:

C:\USERS\ADMIN\DESKTOP\GULPTEST>NPM Install gulp Gulp-sass gulp-autoprefixer browser-sync--save-dev

Browser-sync plugin can help us to refresh our browser automatically.

After the installation is complete, create a new folder under the Gulptest folder app, store our HTML and so on, then create a new file gulpfile.js.

Next is the key gulpfile how to write, first introduce the plugin:

var gulp = require (' Gulp '); var sass = require (' Gulp-sass '); var browsersync = require (' Browser-sync '); var autoperfixer = require (' gulp-autoperfixer ');

Then build a Browsersync instance of reload:

var reload = browsersync.reload;

You can then write the task, for example, to automatically compile Less/sass after modifying the file:

//Less compile taskGulp.task (' less ',function() {//Create a Gulp task with the task name ' less ' and then a callback function    returnGULP.SRC (Paths)//Gulp Task operation source file ' paths '. Pipe (less ())//perform less compilation. Pipe (Gulp.dest ('./css '));//Gulp new file for task output});//Watch Monitor TaskGulp.task (' Watch ',function(){//Create a second gulp task, the task name is ' Watch ', and then a callback functionGulp.watch (paths,[' less ');//Gulp Watch monitoring, the file changes immediately after the re-execution of the less task can refer to http://www.gulpjs.com.cn/docs/api/});//gulp.watch (' Default ', [' less ']);Gulp.task (' Default ', [' less ', ' watch ']);//The default task of the Gulp is equivalent to the Glup's execution entry. Then put the less task and watch in, the script will perform both tasks

A few task codes are pasted directly below:

One, compression CSS

var minifycss = require (' gulp-minify-css '); // reference Plug-in, npm install--save-dev gulp-minify-css required function () {return// Compressed file // Execute compression // output folder });

Second, compression JS

varConcat = require (' Gulp-concat ')), Uglify= Require (' gulp-uglify '), rename= Require (' Gulp-rename ');//reference Plug-in, npm install--save-dev xxxxxx requiredGulp.task (' Minifyjs ',function() {    returnGULP.SRC (' Src/*.js ')//the source file for the operation. Pipe (Concat (' Main.js '))//Merge all js to Main.js. Pipe (Gulp.dest (' Minified/js '))//output main.js to folder. Pipe (rename ({suffix:'. Min '}))//Rename the file name after compression. Pipe (Uglify ())//Compression. Pipe (Gulp.dest (' Minified/js '));//Output});

Third, empty the output directory

vardel=require( 'del' );
Gulp.task (' Clean ',function() { returnDel ([' DST ']); ' DST ' is a directory});
Four, compressed pictures
Const IMAGEMIN = require (' gulp-imagemin '); Gulp.task (function() {    return GULP.SRC (' src/images/* ')           . Pipe (Imagemin ())           . Pipe (Gulp.dest (' dist/images '));});


Five, compressed HTML
varGulp = require (' Gulp ')), Htmlmin= Require (' Gulp-htmlmin '); Gulp.task (' Htmlmin ',function () {    varOptions ={removecomments:true,//Clear HTML CommentsCollapsewhitespace:true,//Compress HTMLCollapsebooleanattributes:true,//omit the value of the Boolean attribute <input checked= "true"/> ==> <input/>Removeemptyattributes:true,//Delete all spaces as attribute values <input id= ""/> ==> <input/>Removescripttypeattributes:true,//Delete <script> type= "Text/javascript"Removestylelinktypeattributes:true,//Remove the Type= "Text/css" from <style> and <link>MINIFYJS:true,//Compress page JSMINIFYCSS:true//Compress page CSS    }; GULP.SRC (' Src/*.html '). Pipe (Htmlmin (options)). Pipe (Gulp.dest (' DST '));});


Vi. Merging of documents
var concat = require (' Gulp-concat '); Gulp.task (function  () {    gulp.src (' src/ Js/*.js ')        . Pipe (concat (' all.js '))// merged file name        . Pipe (Gulp.dest (' Dist/js ')) ;});


Vii. CSS automatically handles browser prefixes, such as adding-webkit-to resolve browser compatibility issues
var autoprefixer = require (' gulp-autoprefixer '); Gulp.task (function  () {    GULP.SRC (' css/index.css ')        . Pipe (Autoprefixer ())        . Pipe (Gulp.dest (' dist/css '));});


Eight, add MD5 stamp to file
var rev = require (' Gulp-rev '); Gulp.task (function() {    return GULP.SRC ([Config.src + Config.resource])        . Pipe (rev ())  // plus MD5 stamp        . Pipe ( Gulp.dest (Config.app))// output file        . Pipe (Rev.manifest ())//  Generates Rev-manifest.json, which is used to replace the MD5 file path referenced in the HTML CSS file        . Pipe (Gulp.dest (Config.rev))//  Rev-manifest.json file in Rev directory });


Nine, the HTML CSS file to replace the path
var revcollector = require (' gulp-rev-collector '); Gulp.task (function() {     return // read Rev-manifest.json files and files that need to be replaced by file names         . Pipe (Revcollector ({            true        // ) substitution of reference names within the execution file        /// Replace the file output directory });


Ten. Automatically refresh the browser after modifying the file
Browsersync = require (' Browser-sync '); var reload = browsersync.reload;gulp.task (' watch ',function() {    Browsersync ({        server:{            baseDir:'./src ' // set the project root directory, starting a server         }    });    Gulp.watch (' src/*.html ', reload); // });


When the set file changes, a local server localhost:3000 is automatically started, and then the directory in the Basedir is read.

If your files are on the server, the code needs to be modified so that

// Agent function  () {    browsersync.init ({        "your domain name or IP"    }); Gulp.watch (' src/*.html ', reload); // listen to HTML files, file changes automatically refresh the browser page immediately });

and several Gulp commands:

Gulp.task (name, FN)// Create a new Gulp task, name is task name, FN callback function gulp.run (Tasks ...) // using Run in Gulp in the new version of running multiple tasks in parallel as much as possible will issue a warning, so that we can use start instead of Gulp.watch (glob, FN//) execute FN When glob content is changed gulp.src (glob) // returns a readable stream gulp.dest (glob) // returns a writable stream

After writing the Gulpfile, you can execute gulp in cmd to complete the command.

ending~

Automated front-end build tool--gulp

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.