var gulp = require('gulp');//引用gulp
var $ = require('gulp-load-plugins')();
var open = require('open');
//创建app对象,定义项目路径
var app = {
srcPath:'src/',
devPath:'build/',
prdPath:'dist/'
};
//同步lib
gulp.task('lib',function(){
gulp.src('bower_components/**/*.js')
.pipe(gulp.dest(app.devPath+'vendor'))
.pipe(gulp.dest(app.prdPath+'vendor'))
.pipe($.connect.reload());,//设置分类重载
});
//同步html
gulp.task('html',function (){
gulp.src(app.srcPath+'/**/*.html')
.pipe(gulp.dest(app.devPath))
.pipe(gulp.dest(app.prdPath))
.pipe($.connect.reload());
});
//同步json
gulp.task('json',function(){
gulp.src(app.srcPath+'data/**/*.json')
.pipe(gulp.dest(app.devPath+'data'))
.pipe(gulp.dest(app.prdPath+'data'))
.pipe($.connect.reload());
});
//同步less,并编译成css
gulp.task('less',function(){
gulp.src(app.srcPath+'style/index.less')
.pipe($.less())
.pipe(gulp.dest(app.devPath+'css'))
.pipe($.cssmin())
.pipe(gulp.dest(app.prdPath+'css'))
.pipe($.connect.reload());
});
//同步js文件,并合并输出到生产环境和开发环境
gulp.task('js',function(){
gulp.src(app.srcPath+'script/**/*.js')
.pipe($.concat('index.js'))
.pipe(gulp.dest(app.devPath+'js'))
.pipe($.uglify())
.pipe(gulp.dest(app.prdPath+'js'))
.pipe($.connect.reload());
});
//同步并压缩图片
gulp.task('img',function(){
gulp.src(app.srcPath+'img/**/*')
.pipe(gulp.dest(app.devPath+'img'))
.pipe($.imagemin())
.pipe(gulp.dest(app.prdPath+'img'))
.pipe($.connect.reload());
});
//同步全部
gulp.task('build',['img','js','less','json','html','lib']);
//清除同步
gulp.task('clean',function(){
gulp.src([app.devPath+'/*',app.prdPath+'/*'])
.pipe($.clean());
});
//定义服务对象
gulp.task('serve',function(){
$.connect.server({
root:[app.devPath],
livereload:true,
port:8081
});
open('http://localhost:8081');
});
//监听文件变化
gulp.watch('bower_components/**/*',['lib']);
gulp.watch(app.srcPath+'/**/*.html',['html']);
gulp.watch(app.srcPath+'style/**/*.less',['less']);,
gulp.watch(app.srcPath+'script/**/*.js',['script']);
gulp.watch(app.srcPath+'data/**/*.json',['json']);
gulp.watch(app.srcPath+'img/**/*,['img']);
项目结构:
主要目的是令到src,build,dist三个目录的结构能够随着修改自动增减同步。
目录最终效果:
注:因为之前设置了server对象,所以相当于有了一个web容器,就不再需要找什么Apache,tomcat之类的东西了,这一点相当屌。