Gulp Installation and use

Source: Internet
Author: User

Gulp Installation and use

Test environment

    • mac:10.10.4
    • gulp:3.9.0

Time: August 15, 2015 18:07:08

Installing Gulp
sudo npm install --global gulpnpm install --save-dev gulp

Input gulp -v , display version description successful installation

Using Gulp

Create a file in the project root directory gulpfile.js

varrequire(‘gulp‘);//引用gulpgulp.task(‘default‘function() {//创建一个task任务  // place code for your default task here});

Enter the directory where the terminal is gulpfils.js located.

Execution, gulp he will be executed by default default , if there is no default task, it will be an error;gulp default

Overall file structure

Root |----gulpfils.JS |----app       |----Hello.txt       |----New             |---- World.txt
Src/dest

gulp.src: File Source

gulp.dest: Destination file path

The file is transferred from the file source to the destination, which can be said to be copied because the source file is still in.

App Catalog

app   | - - - - hello    txt  |  - - - -       new  |  - - - - world   txt   
gulp.task(‘default‘,function(){  gulp.src(‘app/hello.txt‘) .pipe(gulp.dest(‘core‘));//最终文件路径`core/hello.txt`});
gulp.task(‘default‘,function(){  gulp.src(‘app/hello.txt‘) .pipe(gulp.dest(‘core/hello.txt‘));//最终文件路径`core/hello.txt/hello.txt`});

Working with multiple files

gulp.task(‘default‘,function(){  gulp.src(‘app/**‘) .pipe(gulp.dest(‘core‘));//最终文件路径`core/hello.txt/hello.txt`});

After execution, the core directory

core|----hello.txt  |----new       |----world.txt

The following SRC explanations are quoted from the peerless

  • *Can match,,, a.js x.y abc abc/ but not matcha/b.js
  • *.*Can match,, a.js style.css a.b ,x.y
  • */*/*.jsCan match a/b/c.js , x/y/z.js can't match a/b.js ,a/b/c/d.js
  • **Can match,,,, abc a/b.js a/b/c.js x/y/z x/y/z/a.b can be used to match all directories and files
  • **/*.jsCan match,, foo.js a/foo.js a/b/foo.js ,a/b/c/foo.js
  • a/**/zCan match,, a/z a/b/z a/b/c/z ,a/d/g/h/j/k/z
  • a/**b/zCan match a/b/z , a/sb/z but not match a/x/sb/z , because only a single * * appears alone to match a multilevel directory
  • ?.jsCan match a.js , b.js andc.js
  • a??Can match a.b , abc but cannot match ab/ , because it does not match the path delimiter
  • [xyz].jsOnly matches,,, x.js y.js z.js does not match, xy.js xyz.js etc., the entire bracket represents only one character
  • [^xyz].jsCan match a.js , b.js , c.js etc, cannot match x.js , y.js andz.js

Arrays can be used when there are multiple matching patterns

//使用数组的方式来匹配多种文件gulp.src([‘js/*.js‘,‘css/*.css‘,‘*.html‘])

An advantage of using an array is that it is easy to use an exclusion pattern, plus a single matching pattern in the array! That is, the exclusion pattern, which excludes the match from the matching results, and note that the exclusion pattern cannot be used in the first element of the array.

gulp.src([‘*.js‘,‘!b*.js‘//匹配所有js文件,但排除掉以b开头的js文件gulp.src([‘!b*.js‘,‘*.js‘//不会排除任何文件,因为排除模式不能出现在数组的第一个元素中
logOutput
  console.log("my log");
execExecute command line
varrequire(‘child_process‘).exec;gulp.task(‘default‘function() {exec(‘mkdir mygulp‘);});

Execution gulp , you can see that a file is created under the current directory mygulp .

If you want a callback, you can do this.

exec(‘rm -R mygulpfile‘,function (error, stdout, stderr){      if (error !== null) {        console.log("error: "error);      }else{        console.log("ok");      }  });
Execute gulp incoming parameter \ receive parameter
varrequire(‘gulp‘),        require(‘yargs‘).argv;    gulp.task(‘hello_task‘,function(){    if(argv.test) {      var info = argv.test;      console.log(‘收到的参数:‘+info);    else {      console.log(‘输入错误 请输入 gulp hello_task --test hellotest‘);    }    });

Note: yargs the execution of the time may be error, according to the terminal prompt operation.

Watch

Website

Monitor file changes

Here's app/hello.txt an example of listening.

gulp.task(‘watch‘function () {    gulp.watch(‘app/hello.txt‘,function(file){      //变化类型 added为新增,deleted为删除,changed为改变      //变化的文件的路径    });});

Execution gulp watch .

When you hello.txt add a rowhi World

Terminal output

[15:43:16] Using gulpfile ~/root/gulpfile.js[15:43:16‘watch‘...[15:43:16‘watch‘10 mschanged //修改了文件~/root/app/hello.txt //文件路径
Plug-in use

For example, app under Folders, replace all files with helloWorld helloChina .

Here is the use of gulp-replace plug-ins, how to use, the official website has detailed documentation

Install gulp-replace : Execute npm install --save-dev gulp-replace , require permission, add in front sudo .

   varrequire(‘gulp‘),       require(‘gulp-replace‘);    gulp.task(‘replace_code‘,function(){      gulp.src(‘app/**‘)      .pipe(replace("helloWorld","helloChina"))      .pipe(gulp.dest(‘app‘))    });
Merge task execution

At this point, if there are two tasks, ' Task1 ', ' Task2 ', execute a command to execute them both.

gulp.task(‘task3‘, [‘task1‘,‘task2‘]);

Or

gulp.task(‘task3‘, [‘task1‘,‘task2‘],function(){  //coding});

In terminal input gulp task3 , task1 and task2 will execute

Multiple tasks are executed sequentially

Reference website

  • With callback

    // run a command in a shellvarrequire(‘child_process‘).exec;gulp.task(‘jekyll‘function(cb) {// build Jekyllexec(‘jekyll build‘function(err) {  ifreturn// return error  // finished task});});
      • return stream
    gulp.task(‘somename‘function() {var stream = gulp.src(‘client/**/*.js‘)             .pipe(minify())             .pipe(gulp.dest(‘build‘return stream;});
      • Back to Promise
    varrequire(‘q‘);gulp.task(‘somename‘function() {  var deferred = Q.defer();  // do async stuff setTimeout(function() {   1);return deferred.promise;});
After you execute Task1, you can perform Task2

Here 执行one后才能执行two for example

varGulp =require(' Gulp ');//takes in a callback so the engine knows when it ' ll is doneGulp.task (' One ', function(CB) {    //Do stuff--async or otherwiseCB (ERR);//If ERR is not null and not undefined, the run would stop, and note that it failed});//Identifies a dependent task must be complete before this one beginsGulp.task (' both ', [' One '], function() {    //Task ' One ' is do now}); Gulp.task (' Default ', [' One ',' both ']);

Or

(Personal tests found the following can also be achieved, and 被依赖的task返回文件流 )

varrequire(‘gulp‘);gulp.task(‘one‘function() {    return gulp.src(‘client/**/*.js‘)                 .pipe(gulp.dest(‘build‘));});gulp.task(‘two‘, [‘one‘function() {    // task ‘one‘ is done now});
Gulp Personal Understanding

Gulp can be seen as a conveyor belt, which simply transmits (copies) files from a to B, while others do not.

If you want to complete the text replacement, compression and other functions, install the plug-in on the belt, the plug-in completed.

Reference

Gulp Official website

Plug - ins

Glob

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Gulp Installation and use

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.