gulp入门基础

gulp入门基础

gulp是前端开发过程中经常要用到的工具,非常值得花时间去掌握。利用gulp,我们可以使产品流程脚本化,节约大量的时间,有条不紊地进行业务开发。本文简单讲一下入门gulp需要掌握的东西。

安装gulp

首先,我们需要在全局安装gulp。

1
npm install -g gulp

然后,我们切到项目根目录,在项目中也进行gulp的安装,表明项目对gulp的依赖。

1
npm install --save-dev gulp

接着,我们在项目根目录里新建一个gulpfile.js文件,这个是gulp的配置文件。

使用gulp

学习gulp的使用,我们需要先学习好常用的语法。

gulp.src(globs[, options])

输出符合所匹配模式(glob)的文件。将返回一个stream,可以被piped传递到其他gulp插件中继续操作。

gulp.task(name[, deps], fn)

定义一个gulp任务,name是任务名称。[, deps]是任务依赖。fn是任务回调函数。
(1)任务依赖的形式可以是:

1
2
3
4
5
6
7
8
gulp.task('two', ['one'], function() {
// 'one' 完成后
});
gulp.task('one', function(cb) {
// cb();
// return stream;
// return promise;
});

其中one应该使用一个callback,或者返回一个promise 或stream,表明依赖的任务完成了。
(2)回调函数体会是这种形式:

1
gulp.src().pipe(someplugin())

gulp.dest(path[, options])

将pipe进来的stream输出文件到指定的路径下,如:

1
2
3
gulp.src('./client/templates/*.jade')
.pipe(jade())
.pipe(gulp.dest('./build/templates'))

gulp.watch

gulp.watch(glob [, opts], tasks)

监视文件,并且在文件发生改动时候执行一个或者多个task。监听change事件实现。

1
2
3
4
var watcher = gulp.watch('js/**/*.js', ['uglify','reload']);
watcher.on('change', function(event) {
console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
});

gulp.watch(glob [, opts, cb])

监视文件,并且在文件发生改动时候执行回调函数cb。

1
2
3
gulp.watch('js/**/*.js', function(event) {
console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
});

gulp.run

gulp模块的run方法,表示要执行的任务。可能会使用单个参数的形式传递多个任务。任务是尽可能多的并行执行,并且可能不会按照指定的顺序执行。当不需要指定执行顺序时,可以适当使用。

1
gulp.run('task1','task2','task3');

gulp使用技巧

替代任务依赖写法

我们需要让任务有秩序地执行,那么可以使用第三方插件gulp-sequence。

1
2
// 如果使用gulp-sequence,就不需要附加任务依赖了。数组内的任务平行执行,数组外的按顺序执行。所以这里是svgstore、uglify-js并行执行,然后执行public任务。
gulp.task('sequence1', gulpSequence(['svgstore', 'uglify-js'], 'public'));

修复gulp.watch方法只执行一次的问题

利用gulp-watch,gulp-batch两个工具,用法如下:

1
2
3
4
5
6
// 当监听到svgs目录下任意svg文件变动时,执行svgstore任务
gulp.task('watch', function() {
watch('./assets/svgs/*.svg', batch(function(events, done) {
gulp.start('svgstore', done);
}));
});

扫一扫下方小程序码或搜索Tusi博客,即刻阅读最新文章!

Tusi博客

# gulp
You forgot to set the qrcode for Alipay. Please set it in _config.yml.
You forgot to set the qrcode for Wechat. Please set it in _config.yml.
You forgot to set the business and currency_code for Paypal. Please set it in _config.yml.
You forgot to set the url Patreon. Please set it in _config.yml.
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×