gulp 常见插件及做用javascript
dest方法将管道的输出写入文件,同时将这些输出继续输出,因此能够依次调用屡次dest方法,将输出写入多个目录。若是有目录不存在,将会被新建。css
gulp.src('./client/templates/*.jade') .pipe(jade()) .pipe(gulp.dest('./build/templates')) .pipe(minify()) .pipe(gulp.dest('./build/minified_templates'));
task方法用于定义具体的任务。它的第一个参数是任务名,第二个参数是任务函数。下面是一个很是简单的任务函数。
gulp.task('greet', function () { console.log('Hello world!'); });
task方法还能够指定按顺序运行的一组任务。html
task方法的回调函数,还能够接受一个函数做为参数,这对执行异步任务很是有用。java
// 执行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 }); });
若是一个任务的名字为default,就代表它是“默认任务”,在命令行直接输入gulp命令,就会运行该任务。
gulp.task('default', function () { // Your default task });
watch方法用于指定须要监视的文件。一旦这些文件发生变更,就运行指定任务。
gulp-load-plugins 模块gulp.task('watch', function () { gulp.watch('templates/*.tmpl.html', ['build']); });
通常状况下,gulpfile.js中的模块须要一个个加载。shell
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模块之外,还加载另外三个模块。json
这种一一加载的写法,比较麻烦。使用gulp-load-plugins模块,能够加载package.json文件中全部的gulp模块。上面的代码用gulp-load-plugins模块改写,就是下面这样。gulp
gulp-livereload模块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')); });
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()); });