gulp构建前端项目中常见插件的用法
- 入门指南 - 如何开始使用 gulp
- API 文档 - 学习 gulp 的输入和输出方式
- CLI 文档 - 学习如何执行任务(task)以及如何使用一些编译工具
- 编写插件 - 所以,你已经在写一个 gulp 插件了么? 去这儿看一些基本文档,并了解下什么样的事情不应该做
在项目中,我们主要需要用到的构建插件有代码合并、压缩,图片合并,文件复制、删除,代码检查、监听等,以下是我在一些简单项目中gulpfile.js中的一些插件的配置及用法
var gulp = require('gulp'),
less = require('gulp-less'),
lessFunctions = require('less-plugin-functions'),
lessFn = new lessFunctions(),
spritesmith = require('gulp.spritesmith'),
minifycss = require('gulp-minify-css'),
uglify = require('gulp-uglify'),
concat = require('gulp-concat'),
rename = require('gulp-rename'),
copy = require('gulp-contrib-copy'),
processhtml = require('gulp-processhtml'),
clean = require('gulp-clean'),
closureCompiler = require('gulp-closure-compiler');
gulpSequence = require('gulp-sequence');
gulp.task('sprite', function () {
var spriteData = gulp.src('src/images/slice/*.png').pipe(spritesmith({
imgName: '../images/sprite.png',
cssName: 'sprite.less',
cssFormat: 'less',
padding: 8,
cssVarMap: function (sprite) {
sprite.name = 'icon-' + sprite.name;
}
}));
return spriteData.pipe(gulp.dest('src/images/'));
});
gulp.task('less', ['sprite'], function () {
gulp.src('src/less/combine.less')
.pipe(less({
plugins: [lessFn]
}))
.pipe(gulp.dest('src/css'));
});
gulp.task('js', function () {
return gulp.start(['js:vendor', 'js:app:mix']);
});
gulp.task('js:vendor', function () {
return gulp.src([
'src/js/vendor/jquery-3.1.1.min.js',
'src/js/vendor/fastclick.min.js'
])
.pipe(concat('vendor.min.js'))
.pipe(gulp.dest('dist/js'));
});
gulp.task('js:app:concat', function () {
return gulp.src([
'src/js/raycloud.util.ap.js',
'src/js/index.js'
])
.pipe(concat('app.js'))
.pipe(gulp.dest('src/js'));
});
gulp.task('js:app:mix', ['js:app:concat'], function () {
return gulp.src([
'src/js/app.js'
])
.pipe(closureCompiler({
compilerPath: 'bower_components/closure-compiler/closure-compiler-v20161024.jar',
fileName: 'app.min.js'
}))
.pipe(gulp.dest('dist/js'))
});
gulp.task('css', ['less'], function () {
return gulp.src('src/css/*.css')
.pipe(concat('combine.css'))
.pipe(rename({suffix: '.min'}))
.pipe(minifycss())
.pipe(gulp.dest('dist/css'));
});
gulp.task('html', function () {
return gulp.src('src/*.html')
.pipe(processhtml())
.pipe(gulp.dest('dist'));
});
gulp.task('copy', function () {
gulp.src([
'src/images/*',
'!src/images/*.less',
'!src/images/slice'
]).pipe(copy()).pipe(gulp.dest('dist/images/'));
});
gulp.task("clean", function () {
return gulp.src('dist')
.pipe(clean());
});
gulp.task('watch', function () {
gulp.watch('src/**/*.less', ['less']);
});
//开发环境
gulp.task('default', function () {
return gulp.start(['sprite', 'less', 'watch']);
});
//生产环境
gulp.task('build', gulpSequence('clean', 'sprite', 'less', 'js', 'css', 'html', 'copy'));