作为前端开发必备的构建工具gulp和grunt,对于做前端的人肯定再熟悉不过,至少是非常熟悉grunt。
目前项目中less文件编译工具是使用的grunt,但是效率有点低,这才开始研究如何提交编译速度的,当然这时才看到gulp。
一、Gulp区别于grunt
- 易用 Gulp相比Grunt更简洁,而且遵循代码优于配置策略,维护Gulp更像是写代码。
- 高效 Gulp相比Grunt更有设计感,核心设计基于Unix流的概念,通过管道连接,不需要写中间文件。
- 高质量 Gulp的每个插件只完成一个功能,这也是Unix的设计原则之一,各个功能通过流进行整合并完成复杂的任务。例如:Grunt的imagemin插件不仅压缩图片,同时还包括缓存功能。他表示,在Gulp中,缓存是另一个插件,可以被别的插件使用,这样就促进了插件的可重用性。目前官方列出的有673个插件。
- 易学 Gulp的核心API只有5个,掌握了5个API就学会了Gulp,之后便可以通过管道流组合自己想要的任务。
gulp.task
gulp.run
gulp.watch
gulp.src
gulp.dest
二、两者不同的I/O流程
- Grunt的I/O过程中会产生一些临时文件,一些任务生成临时文件,其它任务可能会基于临时文件再做处理并生成最终的构建后文件。
Gulp的优势就是利用流的方式进行文件的处理,通过管道将多个任务和操作连接起来,因此只有一次I/O的过程,流程更清晰,如下图所示。
三、文件定义
1. gruntfile.js(gulpfile.js)
2. package.json
/*
*gulpfile.js文件
*/
var gulp = require('gulp');
var less = require('gulp-less');
var concat = require('gulp-concat');
var watch = require('gulp-watch');
//define the task
gulp.task('Less2css', function () {
gulp.src('resources/assets/less/*.less')
.pipe(less())
.pipe(gulp.dest('public/assets/css/'));
});
/*
watch the task,warning: running the task and Less2css and less2 are same,but the first one just compile less file for once, the second can watch the less file changed at any moment
*/
gulp.task('less2', function () {
gulp.watch('resources/assets/less/*.less', ['Less2css']);
});
/*
*gruntfile.js文件
*/
module.exports = function(grunt) {
// Project configuration
grunt.initConfig({
pkg: grunt.file.readJSON('../package.json'),
// less编译自动化
less: {
less2css: {
options: {
},
files: [
{'web/css/school-frontend.css': "web/less/index.less"},
{
expand: true,
cwd: 'web/less/schoolsets/',
src: ['school-frontend-*.less'],
dest: 'web/css/',
ext: '.css'
}
]
},
},
// 监视文件更改
watch: {
scripts: {
files: ['web/less/*.less'],
tasks: ['less:less2css'],
options: {
debounceDelay: 250
}
},
gruntfile: {
files:['Gruntfile.js']
}
}
});
// 设定node_modules目录位置
// grunt.file.setBase('../');
// load plugin
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-newer');
grunt.loadNpmTasks('grunt-contrib-cssmin');
// default task
grunt.registerTask('default', ['watch']);
//grunt.registerTask('less2css', ['less']);
}
四、常用插件安装
例如:
npm install gulp(grunt)
npm install gulp-util(grunt-util)gulp常用的工具库
npm install gulp-uglify(grunt-uglify)压缩JS文件
npm install gulp-concat(grunt-concat)合并JS
npm install gulp-less(grunt-less)将less预处理为css
npm install gulp-watch(grunt-watch)监控文件变化
npm install gulp-minify-css(grunt-minify-css)gulp-minify-css 压缩css
如何更加详细、高级的使用gulp,请自行参考官网资料。
参考资料:
1. https://segmentfault.com/a/1190000002491282
2. http://www.cnblogs.com/rubylouvre/archive/2013/01/13/2858251.html