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()); });