建立:在项目根目录新建一个js文件并命名为gulpfile.js;
方法:gulp只有五个方法:
gulp.task(‘build‘, [‘css‘, ‘js‘, ‘imgs‘]);
gulp.task(‘css‘, [‘greet‘], function () { // Deal with CSS here });
gulp.task(‘watch‘, function () { gulp.watch(‘templates/*.tmpl.html‘, [‘build‘]); });
也可以给watch函数一个回调函数
gulp.watch(‘templates/*.tmpl.html‘, function (event) { console.log(‘Event type: ‘ + event.type); // added, changed, or deleted console.log(‘Event path: ‘ + event.path); // The path of the modified file });
在返回的watcher中添加监听事件:
var watcher = gulp.watch(‘templates/*.tmpl.html‘, [‘build‘]); watcher.on(‘change‘, function (event) { console.log(‘Event type: ‘ + event.type); // added, changed, or deleted console.log(‘Event path: ‘ + event.path); // The path of the modified file });
js/*.js 仅匹配js目录下的所有后缀为.js的文件
基本代码:
var gulp = require(‘gulp‘); var jshint = require(‘gulp-jshint‘); var sass = require(‘gulp-sass‘); var concat = require(‘gulp-concat‘); var uglify = require(‘gulp-uglify‘); var rename = require(‘gulp-rename‘);
常用组件:
gulp-ruby-sass : 支持sass
gulp-minify-css : 压缩css
gulp-jshint : 检查js
gulp-uglify : 压缩js
gulp-concat : 合并文件
gulp-rename : 重命名文件
gulp-htmlmin : 压缩html
gulp-clean : 清空文件夹
Lint任务: //Link任务会检查js/目录下得js文件有没有报错或警告。
gulp.task(‘lint‘, function() { gulp.src(‘./js/*.js‘) .pipe(jshint()) .pipe(jshint.reporter(‘default‘)); });
gulp.task(‘sass‘, function() { gulp.src(‘./scss/*.scss‘) .pipe(sass()) .pipe(gulp.dest(‘./css‘)); // })
gulp.task(‘scripts‘, function() { gulp.src(‘./js/*.js‘) .pipe(concat(‘all.js‘)) .pipe(gulp.dest(‘./dist‘)) .pipe(rename(‘all.min.js‘)) .pipe(uglify()) .pipe(gulp.dest(‘./dist‘)); });
gulp.task(‘default‘, function(){ gulp.run(‘lint‘, ‘sass‘, ‘scripts‘); gulp.watch(‘./js/*.js‘, function(){ gulp.run(‘lint‘, ‘sass‘, ‘scripts‘); }); });
原文:http://www.cnblogs.com/jinkspeng/p/4190391.html