发布于 2016-01-09 21:14:17 | 211 次阅读 | 评论: 0 | 来源: PHPERZ

这里有新鲜出炉的精品教程,程序狗速度看过来!

GulpJS 流构建系统

从头编写HTML\CSS\Javascript是上个世纪的事情了,如今的JavaScript都是通过CoffeeScript这样的支持句法缩写的编辑器写成的。如果你希望写完JavaScript能够一个工具完成代码清理优化工作,Gulp 就是你的不二之选,GulpJS类似Ant或Maven之于Java。


常见的插件基本使用

  • 压缩js文件 gulp-uglify 使用方法 .pipe(uglify())

  • 变异sass gulp-sass 使用方法 .pipe(sass())

  • 压缩css文件 gulp-minify-css 使用方法 .pipe(minifyCSS())

  • 添加CSS浏览器前缀 gulp-autoprefixer 使用方法 .pipe(autoprefixer({browsers: 'last 2 versions'}))

  • 压缩图片 gulp-imagemin 使用方法 .pipe(imagemin({progressive:true}))

  • 合并文件 gulp-concat 使用方法 .pipe(concat('index.js'))

  • 重命名文件 gulp-rename 使用方法 .pipe(rename('index.min.js'))

  • 压缩html文件 gulp-html-minify 使用方法 .pipe(htmlminify())

  • js代码检查 gulp-jshint 使用方法 .pipe(jshint()).pipe(jshint.reporter('default'));

提升效率

  • gulp-livereload当文件变化之后,自动刷新页面,需要结合谷歌浏览器的livereload插件使用,首先使用livereload.listen();监听,然后将代码pipelivereload(),示例代码如下:

    gulp.task('htmlwatch', function () {
        gulp.src('public/web/*.html').pipe(livereload());
    })
    
    gulp.task('liveWatch', function () {
        livereload.listen();
        gulp.watch('public/web/*.html', ['htmlwatch']);
    })
    
    //或者
    /*gulp.task('watch', function() {
      // Create LiveReload server
      livereload.listen();
      // Watch any files in dist/, reload on change
      gulp.watch(['dist/**']).on('change', livereload.changed);
    });*/
  • gulp.watch监听文件的变化情况,但是gulp.watch不能够自动启动,需要使用另外的任务启动,代码如下:

    // 在命令行使用 gulp auto 启动此任务
    gulp.task('auto', function () { 
        // 监听文件修改,当文件被修改则执行 script 任务
        gulp.watch('js/*.js', ['script']) 
    })
  • 让命令输出带有颜色的文字 gulp-util

  • gulp-watch-pathstream-combiner2同时使用 基本原理:使用gulp-watch-path处理gulp.watch返回的事件,得到变化的路径,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('messsage:'+err.message);
        gutil.log('plugin:'+colors.yellow(err.plugin));
    }

    //使用watchjs能够控制单个文件的变化
    gulp.task('watchjs',function(){
        gulp.watch('public/back/**/*',function(event){
            var paths = watchPath(event,'public/back/','dist/back/');
            gutil.log(gutil.colors.green(event.type)+" "+paths.srcPath);//打印变化的类型及文件的路径名称
            gutil.log('Dist '+paths.distPath);//打印目标路径
            //将操作放在combined中监视
            var combined = combiner.obj([
                gulp.src(paths.srcPath),uglify(),gulp.dest(paths.distDir)
            ]);
    
            combined.on('error',handleError);
        })
    })
  • gulp-connect这个插件不需要浏览器插件就可以检测文件是否变动刷新页面,但是与gulp-watch-path最大的不同在于gulp-connect需要监听默认的端口,一旦网页部署到服务器上之后,或者使用了后端的资源时,就会存在监听端口的冲突。示例代码如下:

    gulp.task('connectDev', function() {
    connect.server({
        root: 'public/web/',
        port: 8081,
        livereload: true
    });
    });
    
    gulp.task('reload-dev',function() {
        gulp.src('public/web/**/*.*')
            .pipe(connect.reload());
    });
    
    // Watch
    gulp.task('watch', function() {
        //监听生产环境目录变化
        gulp.watch('public/web/**/*.*',['reload-dev']);
    })

    //测试服务器
    gulp.task('default-live', ['connectDev', 'watch']);
  • gulp-plumber添加到任务中,阻止 gulp 插件发生错误导致进程退出并输出错误日志。代码中的error对象能够获取到错误的信息,特别说明:gulp-plumber使得,如果监听(watch)事件并不会因为出现了错误就停止运行,gulp-notify专门的提示信息,示例代码如下:

    gulp.task('mijs',function(){
        return gulp.src('public/web/js/common.js')
            .pipe(plumber({errorHandler: notify.onError('Error: <%= error %> ')}))
            .pipe(uglify())
            .pipe(gulp.dest('public/web/js/'));
    })

摘抄的例子

    /*!
     * gulp
     * $ npm install gulp-ruby-sass gulp-autoprefixer gulp-minify-css gulp-jshint gulp-concat gulp-uglify gulp-imagemin gulp-notify gulp-rename gulp-livereload gulp-cache del --save-dev
     */
    // Load plugins
    var gulp = require('gulp'),
        sass = require('gulp-ruby-sass'),
        autoprefixer = require('gulp-autoprefixer'),
        minifycss = require('gulp-minify-css'),
        jshint = require('gulp-jshint'),
        uglify = require('gulp-uglify'),
        imagemin = require('gulp-imagemin'),
        rename = require('gulp-rename'),
        concat = require('gulp-concat'),
        notify = require('gulp-notify'),
        cache = require('gulp-cache'),
        livereload = require('gulp-livereload'),
        del = require('del');
    // Styles
    gulp.task('styles', function() {
      return gulp.src('src/styles/main.scss')
        .pipe(sass({ style: 'expanded', }))
        .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
        .pipe(gulp.dest('dist/styles'))
        .pipe(rename({ suffix: '.min' }))
        .pipe(minifycss())
        .pipe(gulp.dest('dist/styles'))
        .pipe(notify({ message: 'Styles task complete' }));
    });
    // Scripts
    gulp.task('scripts', function() {
      return gulp.src('src/scripts/**/*.js')
        .pipe(jshint('.jshintrc'))
        .pipe(jshint.reporter('default'))
        .pipe(concat('main.js'))
        .pipe(gulp.dest('dist/scripts'))
        .pipe(rename({ suffix: '.min' }))
        .pipe(uglify())
        .pipe(gulp.dest('dist/scripts'))
        .pipe(notify({ message: 'Scripts task complete' }));
    });
    // Images
    gulp.task('images', function() {
      return gulp.src('src/images/**/*')
        .pipe(cache(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })))
        .pipe(gulp.dest('dist/images'))
        .pipe(notify({ message: 'Images task complete' }));
    });
    // Clean
    gulp.task('clean', function(cb) {
        del(['dist/assets/css', 'dist/assets/js', 'dist/assets/img'], cb)
    });
    // Default task
    gulp.task('default', ['clean'], function() {
        gulp.start('styles', 'scripts', 'images');
    });
    // Watch
    gulp.task('watch', function() {
      // Watch .scss files
      gulp.watch('src/styles/**/*.scss', ['styles']);
      // Watch .js files
      gulp.watch('src/scripts/**/*.js', ['scripts']);
      // Watch image files
      gulp.watch('src/images/**/*', ['images']);
      // Create LiveReload server
      livereload.listen();
      // Watch any files in dist/, reload on change
      gulp.watch(['dist/**']).on('change', livereload.changed);
    });

gulp相关资源集合



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务