流(Stream)能够通过一系列的小函数来传递数据,这些函数会对数据进行修改,然后把修改后的数据传递给下一个函数。
看一个简单例子:
var gulp = require('gulp'),
uglify = require('gulp-uglify');
gulp.task('minify', function () {
gulp.src('js/app.js')
.pipe(uglify())
.pipe(gulp.dest('build'))
});
gulp.src()函数用字符串匹配一个文件或者文件的编号(被称为“glob”),然后创建一个对象流来代表这些文件,接着传递给uglify()函数,它接受文件对象之后返回有新压缩源文件的文件对象,最后那些输出的文件被输入gulp.dest()函数,并保存下来。
想了解更多的关于node stream方面的知识,可以访问stream-handbook。 stream-handbook中文翻译
根据globs提供的文件列表, 得到一个Vinyl文件的stream, 可以按照管道模式给其它插件处理。
gulp.src('client/templates/*.jade')
.pipe(jade())
.pipe(minify())
.pipe(gulp.dest('build/minified_templates'));
将管道中的数据写入到文件夹。
使用orchestrator定义任务。
gulp.task('somename', function() {
// Do stuff
});
deps 是任务数组,在执行本任务时数组中的任务要执行并完成。
监控文件。当监控的文件有所改变时执行特定的任务。
下面的文章总结的几个常见问题的解决方案,非常有参考价值。
https://github.com/gulpjs/gulp/tree/master/docs/recipes#recipes
browserify可以为浏览器编译node风格的遵循commonjs的模块。 它搜索文件中的require()
调用, 递归的建立模块依赖图。
var gulp = require('gulp');
var browserify = require('gulp-browserify');
// Basic usage
gulp.task('scripts', function() {
// Single entry point to browserify
gulp.src('src/js/app.js')
.pipe(browserify({
insertGlobals : true,
debug : !gulp.env.production
}))
.pipe(gulp.dest('./build/js'))
});
gulp的jshint插件。
jshint是一个侦测javascript代码中错误和潜在问题的工具。
用法:
var jshint = require('gulp-jshint');
var gulp = require('gulp');
gulp.task('lint', function() {
return gulp.src('./lib/*.js')
.pipe(jshint())
.pipe(jshint.reporter('YOUR_REPORTER_HERE'));
});
jslint是一个javascript代码质量检测工具。
gulp-jslint是它的gulp插件。
var gulp = require('gulp');
var jslint = require('gulp-jslint');
// build the main source into the min file
gulp.task('default', function () {
return gulp.src(['source.js'])
// pass your directives
// as an object
.pipe(jslint({
// these directives can
// be found in the official
// JSLint documentation.
node: true,
evil: true,
nomen: true,
// you can also set global
// declarations for all source
// files like so:
global: [],
predef: [],
// both ways will achieve the
// same result; predef will be
// given priority because it is
// promoted by JSLint
// pass in your prefered
// reporter like so:
reporter: 'default',
// ^ there's no need to tell gulp-jslint
// to use the default reporter. If there is
// no reporter specified, gulp-jslint will use
// its own.
// specify whether or not
// to show 'PASS' messages
// for built-in reporter
errorsOnly: false
}))
// error handling:
// to handle on error, simply
// bind yourself to the error event
// of the stream, and use the only
// argument as the error object
// (error instanceof Error)
.on('error', function (error) {
console.error(String(error));
});
});
imagemin是压缩图片的工具。
var gulp = require('gulp');
var imagemin = require('gulp-imagemin');
var pngquant = require('imagemin-pngquant');
gulp.task('default', function () {
return gulp.src('src/images/*')
.pipe(imagemin({
progressive: true,
svgoPlugins: [{removeViewBox: false}],
use: [pngquant()]
}))
.pipe(gulp.dest('dist'));
});
sass是编写css的一套语法。 使用它的预处理器可以将sass语法的css处理成css格式。
glup-sass语法:
var gulp = require('gulp');
var sass = require('gulp-sass');
gulp.task('sass', function () {
gulp.src('./scss/*.scss')
.pipe(sass())
.pipe(gulp.dest('./css'));
});
gulp-ruby-sass是另外一款sass的gulp插件, 比glup-sass慢,但是更稳定,功能更多。 它使用compass预处理sass文件,所以你需要安装ruby和compass。
var gulp = require('gulp');
var sass = require('gulp-ruby-sass');
gulp.task('default', function () {
return gulp.src('src/scss/app.scss')
.pipe(sass({sourcemap: true, sourcemapPath: '../scss'}))
.on('error', function (err) { console.log(err.message); })
.pipe(gulp.dest('dist/css'));
});
BrowserSync 是一个自动化测试辅助工具,可以帮你在网页文件变更时自动载入新的网页。
用法:
var gulp = require('gulp');
var browserSync = require('browser-sync');
// Static server
gulp.task('browser-sync', function() {
browserSync({
server: {
baseDir: "./"
}
});
});
// or...
gulp.task('browser-sync', function() {
browserSync({
proxy: "yourlocal.dev"
});
});
还可以使用proxy-middleware
作为http proxy,转发特定的请求。
handlebars是一个模版引擎库, ember.js用它作为前端的模版引擎。
gulp-handlebars编译handlebars文件。
用法:
var handlebars = require('gulp-handlebars');
var wrap = require('gulp-wrap');
var declare = require('gulp-declare');
var concat = require('gulp-concat');
gulp.task('templates', function(){
gulp.src('source/templates/*.hbs')
.pipe(handlebars())
.pipe(wrap('Handlebars.template(<%= contents %>)'))
.pipe(declare({
namespace: 'MyApp.templates',
noRedeclare: true, // Avoid duplicate declarations
}))
.pipe(concat('templates.js'))
.pipe(gulp.dest('build/js/'));
});
用来将HTML 文件中(或者templates/views)中没有优化的script 和stylesheets 替换为优化过的版本。
usemin 暴露两个内置的任务,分别为:
usemin块如下定义:
<!-- build:<pipelineId>(alternate search path) <path> -->
... HTML Markup, list of script / link tags.
<!-- endbuild -->
如
<!-- build:css style.css -->
<link rel="stylesheet" href="http://colobu.com/2014/11/17/gulp-plugins-introduction/css/clear.css"/>
<link rel="stylesheet" href="http://colobu.com/2014/11/17/gulp-plugins-introduction/css/main.css"/>
<!-- endbuild -->
<!-- build:js js/lib.js -->
<script src="http://colobu.com/2014/11/17/lib/angular-min.js"></script>
<script src="http://colobu.com/2014/11/17/lib/angular-animate-min.js"></script>
<!-- endbuild -->
<!-- build:js1 js/app.js -->
<script src="http://colobu.com/2014/11/17/gulp-plugins-introduction/js/app.js"></script>
<script src="http://colobu.com/2014/11/17/gulp-plugins-introduction/js/controllers/thing-controller.js"></script>
<script src="http://colobu.com/2014/11/17/gulp-plugins-introduction/js/models/thing-model.js"></script>
<script src="http://colobu.com/2014/11/17/gulp-plugins-introduction/js/views/thing-view.js"></script>
<!-- endbuild -->
<!-- build:remove -->
<script src="http://colobu.com/2014/11/17/gulp-plugins-introduction/js/localhostDependencies.js"></script>
<!-- endbuild -->
gulp-usemin用法如下:
var usemin = require('gulp-usemin');
var uglify = require('gulp-uglify');
var minifyHtml = require('gulp-minify-html');
var minifyCss = require('gulp-minify-css');
var rev = require('gulp-rev');
gulp.task('usemin', function() {
gulp.src('./*.html')
.pipe(usemin({
css: [minifyCss(), 'concat'],
html: [minifyHtml({empty: true})],
js: [uglify(), rev()]
}))
.pipe(gulp.dest('build/'));
});
uglify是一款javascript代码优化工具,可以解析,压缩和美化javascript。
用法:
var uglify = require('gulp-uglify');
gulp.task('compress', function() {
gulp.src('lib/*.js')
.pipe(uglify())
.pipe(gulp.dest('dist'))
});
在现代javascript开发中, JavaScript脚本正变得越来越复杂。大部分源码(尤其是各种函数库和框架)都要经过转换,才能投入生产环境。
常见的转换情况:
var gulp = require('gulp');
var plugin1 = require('gulp-plugin1');
var plugin2 = require('gulp-plugin2');
var sourcemaps = require('gulp-sourcemaps');
gulp.task('javascript', function() {
gulp.src('src/**/*.js')
.pipe(sourcemaps.init())
.pipe(plugin1())
.pipe(plugin2())
.pipe(sourcemaps.write())
.pipe(gulp.dest('dist'));
});
可以注入css,javascript和web组件,不需手工更新ndex.html。
<!DOCTYPE html>
<html>
<head>
<title>My index</title>
<!-- inject:css -->
<!-- endinject -->
</head>
<body>
<!-- inject:js -->
<!-- endinject -->
</body>
</html>
var gulp = require('gulp');
var inject = require("gulp-inject");
gulp.task('index', function () {
var target = gulp.src('./src/index.html');
// It's not necessary to read the files (will speed up things), we're only after their paths:
var sources = gulp.src(['./src/**/*.js', './src/**/*.css'], {read: false});
return target.pipe(inject(sources))
.pipe(gulp.dest('./src'));
});
为管道中的文件增加header。
var header = require('gulp-header');
gulp.src('./foo/*.js')
.pipe(header('Hello'))
.pipe(gulp.dest('./dist/')
gulp.src('./foo/*.js')
.pipe(header('Hello <%= name %>\n', { name : 'World'} ))
.pipe(gulp.dest('./dist/')
gulp.src('./foo/*.js')
.pipe(header('Hello ${name}\n', { name : 'World'} ))
.pipe(gulp.dest('./dist/')
//
var pkg = require('./package.json');
var banner = ['/**',
' * <%= pkg.name %> - <%= pkg.description %>',
' * @version v<%= pkg.version %>',
' * @link <%= pkg.homepage %>',
' * @license <%= pkg.license %>',
' */',
''].join('\n');
gulp.src('./foo/*.js')
.pipe(header(banner, { pkg : pkg } ))
.pipe(gulp.dest('./dist/')
相应的还有一个gulp-footer
插件。
筛选vinyl stream中的文件。
var gulp = require('gulp');
var jscs = require('gulp-jscs');
var gulpFilter = require('gulp-filter');
gulp.task('default', function () {
// create filter instance inside task function
var filter = gulpFilter(['*', '!src/vendor']);
return gulp.src('src/*.js')
// filter a subset of the files
.pipe(filter)
// run them through a plugin
.pipe(jscs())
// bring back the previously filtered out files (optional)
.pipe(filter.restore())
.pipe(gulp.dest('dist'));
});
只允许改变的文件通过管道。
var gulp = require('gulp');
var changed = require('gulp-changed');
var ngmin = require('gulp-ngmin'); // just as an example
var SRC = 'src/*.js';
var DEST = 'dist';
gulp.task('default', function () {
return gulp.src(SRC)
.pipe(changed(DEST))
// ngmin will only get the files that
// changed since the last time it was run
.pipe(ngmin())
.pipe(gulp.dest(DEST));
});
执行bower安装。
var gulp = require('gulp');
var bower = require('gulp-bower');
gulp.task('bower', function() {
return bower()
.pipe(gulp.dest('lib/'))
});
有条件的执行任务
字符串替换插件。
var replace = require('gulp-replace');
gulp.task('templates', function(){
gulp.src(['file.txt'])
.pipe(replace(/foo(.{3})/g, '$1foo'))
.pipe(gulp.dest('build/file.txt'));
});
可以执行shell命令
exec插件
安装npm和bower包, 如果它们的配置文件存在的话。
var install = require("gulp-install");
gulp.src(__dirname + '/templates/**')
.pipe(gulp.dest('./'))
.pipe(install());
改变管道中的文件名。
var rename = require("gulp-rename");
// rename via string
gulp.src("./src/main/text/hello.txt")
.pipe(rename("main/text/ciao/goodbye.md"))
.pipe(gulp.dest("./dist")); // ./dist/main/text/ciao/goodbye.md
// rename via function
gulp.src("./src/**/hello.txt")
.pipe(rename(function (path) {
path.dirname += "/ciao";
path.basename += "-goodbye";
path.extname = ".md"
}))
.pipe(gulp.dest("./dist")); // ./dist/main/text/ciao/hello-goodbye.md
// rename via hash
gulp.src("./src/main/text/hello.txt", { base: process.cwd() })
.pipe(rename({
dirname: "main/text/ciao",
basename: "aloha",
prefix: "bonjour-",
suffix: "-hola",
extname: ".md"
}))
.pipe(gulp.dest("./dist")); // ./dist/main/text/ciao/bonjour-aloha-hola.md
忽略管道中的部分文件。
提供一些辅助方法。
提供clean功能。
var gulp = require('gulp');
var clean = require('gulp-clean');
gulp.task('clean', function () {
return gulp.src('build', {read: false})
.pipe(clean());
});
连接合并文件。
var concat = require('gulp-concat');
gulp.task('scripts', function() {
gulp.src('./lib/*.js')
.pipe(concat('all.js'))
.pipe(gulp.dest('./dist/'))
});
将一个lodash模版包装成流内容。
安全的声明命名空间,设置属性。
var declare = require('gulp-declare');
var concat = require('gulp-concat');
gulp.task('models', function() {
// Define each model as a property of a namespace according to its filename
gulp.src(['client/models/*.js'])
.pipe(declare({
namespace: 'MyApp.models',
noRedeclare: true // Avoid duplicate declarations
}))
.pipe(concat('models.js')) // Combine into a single file
.pipe(gulp.dest('build/js/'));
});