Gulp: automatic task management tool

Gulp Like Grunt, is also an automatic task runner. It fully draw on the Unix operating system pipe (pipe) thinking, a lot of people think that, in operation, it Grunt than simple.

Gulp need global installed, then install the module in the development of the local directory of the project. First into the project directory, run the following command.

npm install -g gulp

npm install --save-dev gulp

In addition to installing gulp, different tasks also need to install a different plug-in modules gulp. For example, the following code installed gulp-uglify module.

$ npm install --save-dev gulp-uglify

gulpfile.js

Project root directory gulpfile.js, is Gulp profile. Here is a typical gulpfile.js file.

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

gulp.task('minify', function () {
gulp.src('js/app.js')
.pipe(uglify())
.pipe(gulp.dest('build'))
});

In the above code, after gulpfile.js gulp and gulp-uglify loading modules, using the method specified task module gulp task minify. The method has two parameters task, the task name is a first, a second task function. At task function, using the method gulp src module, specify the file to be processed, and then use the pipe method, the output of the previous step into the current input, perform processing chain.

task callback method using two pipe method, that is done two treatments. The first is to use a gulp-uglify processing module, a compression source; The second process is a method of using gulp dest module, the output is written in the previous step a local file, there is build.js (suffix omitted code js) .

Minify task execution, execute the following command in the project directory on it.

$ gulp minify

Can be seen from the above example, GULP full use of the "pipe" thinking, it is a data stream (stream): src method of reading a file produce a data stream, the data stream written to dest file method, the middle number of intermediate steps, each step of the data stream some processing.

Here is another example of a data stream.

gulp.task('js', function () {
return gulp.src('js/*.js')
.pipe(jshint())
.pipe(uglify())
.pipe(concat('app.js'))
.pipe(gulp.dest('build'));
});

The above code uses the command pipe, respectively jshint, uglify, concat three-step process.

The method gulp module

src()

src method gulp module to produce a data stream. It represents the parameter file to be processed, the specified files are converted into a data stream. Written arguments generally have the following form.

  • js / app.js: specify the exact file name.
  • js / * js:. a list of all the js file name suffix.
  • js / ** / * js:. a directory and all subdirectories suffix all the js file named.
  • ! Js / app.js: All files except js / app.js of.
  • . * + (Js | css): Under the root directory of matches, all js or css file name suffix of.

Src method parameters may also be an array for designating a plurality of members.

gulp.src ([ 'js / ** / *. js' , '! js / ** / *. min.js' ])

()

dest method for piping the output written to the file, and will continue to output these outputs, so you can call multiple times in order dest method, the output is written to multiple directories. If the directory does not exist, it will be new.

gulp.src('./client/templates/*.jade')
.pipe(jade())
.pipe(gulp.dest('./build/templates'))
.pipe(minify())
.pipe(gulp.dest('./build/minified_templates'));

dest method may also accepts a second parameter represents configuration objects.

gulp.dest('build', {
cwd: './app',
mode: '0644'
})

Configuration object has two fields. cwd field specifies the write path of the base directory, the default is the current directory; written permission mode field specifies the file, the default is 0777.

task()

The method used to define the specific task of the task. Its first parameter is the task name, the second parameter is the task function. Here is a very simple task function.

gulp.task('greet', function () {
console.log('Hello world!');
});

The method may further task to specify a set of tasks to run in sequence.

gulp.task('build', ['css', 'js', 'imgs']);

The above code first specify the build task, which consists of css, js, imgs composed of three tasks, task method will perform these three tasks concurrently. Note that because each task is an asynchronous call, so there is no way to guarantee the start of js task of running time, it is the task css run over.

If you want each task strict run in sequence before a task can be written as a module dependent tasks later.

gulp.task('css', ['greet'], function () {

});

The above code indicates, css task dependencies greet task, so css will greet run after run is complete.

task callback method can also accept a function as an argument, which is very useful to perform asynchronous tasks.

// 执行shell命令
var exec = require('child_process').exec;
gulp.task('jekyll', function(cb) {
// build Jekyll
exec('jekyll build', function(err) {
if (err) return cb(err); // return error
cb(); // finished task
});
});

If the name of a task for the default, to show that it is "default task", gulp enter commands directly from the command line, it will run the task.

gulp.task('default', function () {
// Your default task
});

// or

gulp.task('default', ['styles', 'jshint', 'watch']);

执行的时候,直接使用gulp,就会运行styles、jshint、watch三个任务。

watch()

watch方法用于指定需要监视的文件。一旦这些文件发生变动,就运行指定任务。

gulp.task('watch', function () {
gulp.watch('templates/*.tmpl.html', ['build']);
});

上面代码指定,一旦templates目录中的模板文件发生变化,就运行build任务。

watch方法也可以用回调函数,代替指定的任务。

gulp.watch('templates/*.tmpl.html', function (event) {
console.log('Event type: ' + event.type);
console.log('Event path: ' + event.path);
});

另一种写法是watch方法所监控的文件发生变化时(修改、增加、删除文件),会触发change事件。可以对change事件指定回调函数。

var watcher = gulp.watch('templates/*.tmpl.html', ['build']);

watcher.on('change', function (event) {
console.log('Event type: ' + event.type);
console.log('Event path: ' + event.path);
});

除了change事件,watch方法还可能触发以下事件。

  • end:回调函数运行完毕时触发。
  • error:发生错误时触发。
  • ready:当开始监听文件时触发。
  • nomatch:没有匹配的监听文件时触发。

watcher对象还包含其他一些方法。

  • watcher.end():停止watcher对象,不会再调用任务或回调函数。
  • watcher.files():返回watcher对象监视的文件。
  • watcher.add(glob):增加所要监视的文件,它还可以附件第二个参数,表示回调函数。
  • watcher.remove(filepath):从watcher对象中移走一个监视的文件。

gulp-load-plugins模块

一般情况下,gulpfile.js中的模块需要一个个加载。

var gulp = require('gulp'),
jshint = require('gulp-jshint'),
uglify = require('gulp-uglify'),
concat = require('gulp-concat');

gulp.task('js', function () {
return gulp.src('js/*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(uglify())
.pipe(concat('app.js'))
.pipe(gulp.dest('build'));
});

上面代码中,除了gulp模块以外,还加载另外三个模块。

这种一一加载的写法,比较麻烦。使用gulp-load-plugins模块,可以加载package.json文件中所有的gulp模块。上面的代码用gulp-load-plugins模块改写,就是下面这样。

var gulp = require('gulp'),
gulpLoadPlugins = require('gulp-load-plugins'),
plugins = gulpLoadPlugins();

gulp.task('js', function () {
return gulp.src('js/*.js')
.pipe(plugins.jshint())
.pipe(plugins.jshint.reporter('default'))
.pipe(plugins.uglify())
.pipe(plugins.concat('app.js'))
.pipe(gulp.dest('build'));
});

上面代码假设package.json文件包含以下内容。

{
"devDependencies": {
"gulp-concat": "~2.2.0",
"gulp-uglify": "~0.2.1",
"gulp-jshint": "~1.5.1",
"gulp": "~3.5.6"
}
}

gulp-livereload模块

gulp-livereload模块用于自动刷新浏览器,反映出源码的最新变化。它除了模块以外,还需要在浏览器中安装插件,用来配合源码变化。

var gulp = require('gulp'),
less = require('gulp-less'),
livereload = require('gulp-livereload'),
watch = require('gulp-watch');

gulp.task('less', function() {
gulp.src('less/*.less')
.pipe(watch())
.pipe(less())
.pipe(gulp.dest('css'))
.pipe(livereload());
});

上面代码监视less文件,一旦编译完成,就自动刷新浏览器。

参考链接

Original: Big Box  Gulp: automatic task management tool


Guess you like

Origin www.cnblogs.com/chinatrump/p/11584953.html