gulp入门代码

/*
gulp学习之路:

问题一:
	*在gulp中用法
问题二:
	gulpfile.js 可以分享给朋友,而且他只需要执行【npm install】

*/
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var minifycss= require('gulp-minify-css');
var imagemin = require('gulp-imagemin');
var less = require('gulp-less');
var autoprefixer = require('gulp-autoprefixer')
var gutil = require('gulp-util')
var watchPath = require('gulp-watch-path')
var combiner = require('stream-combiner2')

var handleError = function (err) {
    var colors = gutil.colors;
    console.log('\n')
    gutil.log(colors.red('Error!'))
    gutil.log('fileName: ' + colors.red(err.fileName))
    gutil.log('lineNumber: ' + colors.red(err.lineNumber))
    gutil.log('message: ' + err.message)
    gutil.log('plugin: ' + colors.yellow(err.plugin))
}
gulp.task('watchjs', function () {
    gulp.watch('ori/js/**/*.js', function (event) {
        var paths = watchPath(event, 'ori/', 'dist/')
        /*
        paths
            { srcPath: 'ori/js/log.js',
              srcDir: 'ori/js/',
              distPath: 'dist/js/log.js',
              distDir: 'dist/js/',
              srcFilename: 'log.js',
              distFilename: 'log.js' }
        */
        gutil.log(gutil.colors.green(event.type) + ' ' + paths.srcPath)
        gutil.log('Dist ' + paths.distPath)

        var combined = combiner.obj([
            gulp.src(paths.srcPath),
            uglify(),
            gulp.dest(paths.distDir)
        ])

        combined.on('error', handleError)
    })
})
gulp.task('script', function() {
  // 将你的默认的任务代码放在这
  gulp.src('ori/js/*.js')
  	  .pipe(uglify())
  	  .pipe(gulp.dest('dist/js'))
});

gulp.task('css',function(){
	gulp.src('ori/css/*.css')
		.pipe(autoprefixer({
              browsers: 'last 2 versions'
            }))
		.pipe(minifycss())
		.pipe(gulp.dest('dist/css'))
});

gulp.task('image',function(){
	gulp.src('ori/img/*.*')
		.pipe(imagemin({
			progressive:true
		}))
		.pipe(gulp.dest('dist/img'))
});

gulp.task('less',function(){
	gulp.src('ori/less/**.less')
		.pipe(less())
		.pipe(autoprefixer({
              browsers: 'last 2 versions'
            }))
		.pipe(minifycss())
		.pipe(gulp.dest('dist/css'))
});

gulp.task('auto',function(){
	gulp.watch('ori/js/*.js', ['script']);
	gulp.watch('ori/css/*.css',['css']);
	gulp.watch('ori/img/*.*',['image']);
	gulp.watch('ori/less/**.less',['less'])
});

gulp.task('default',['script','auto','css','image','less','watchjs']);

  

posted @ 2018-04-26 09:36  cao_zhen  阅读(155)  评论(0编辑  收藏  举报