您现在的位置:首页 >> 前端 >> 内容

gulp插件

时间:2017/7/1 9:27:00 点击:

  核心提示:gulp插件。gulp API流(Stream)能够通过一系列的小函数来传递数据,这些函数会对数据进行修改,然后把修改后的数据传递给下一个函数。看一个简单例子:var gulp = require(g...

gulp插件。

gulp API

流(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中文翻译

gulp.src(globs[, options])

根据globs提供的文件列表, 得到一个Vinyl文件的stream, 可以按照管道模式给其它插件处理。

gulp.src('client/templates/*.jade')
  .pipe(jade())
  .pipe(minify())
  .pipe(gulp.dest('build/minified_templates'));

gulp.dest(path[, options])

将管道中的数据写入到文件夹。

gulp.task(name[, deps], fn)

使用orchestrator定义任务。

gulp.task('somename', function() {
  // Do stuff
});

deps是任务数组,在执行本任务时数组中的任务要执行并完成。

gulp.watch(glob [, opts], tasks), gulp.watch(glob [, opts, cb])

监控文件。当监控的文件有所改变时执行特定的任务。

Recipes

下面的文章总结的几个常见问题的解决方案,非常有参考价值。
https://github.com/gulpjs/gulp/tree/master/docs/recipes#recipes

gulp-browserify

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

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'));
});

gulp-jslint

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

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'));
});

glup-sass

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'));
});

browser-sync

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,转发特定的请求。

gulp-handlebars

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/'));
});

gulp-usemin

用来将HTML 文件中(或者templates/views)中没有优化的script 和stylesheets 替换为优化过的版本。
usemin 暴露两个内置的任务,分别为:

  • useminPrepare 为将指定文件中的 usemin block 转换为单独的一行(优化版本)准备配置。这通过为每个优化步骤生成名为 generated 的子任务来完成。usemin 使用优化版本替换 usemin 块,如果在磁盘上可以找到 revisioned 版本,则替换为 revisioned 版本。

    usemin块如下定义:

    
    ... HTML Markup, list of script / link tags.
    

    
    
    <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><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><script src="http://colobu.com/2014/11/17/gulp-plugins-introduction/js/localhostDependencies.js"></script>

    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/'));
    });

    gulp-uglify

    uglify是一款javascript代码优化工具,可以解析,压缩和美化javascript。
    用法:

    var uglify = require('gulp-uglify');
    
    gulp.task('compress', function() {
      gulp.src('lib/*.js')
        .pipe(uglify())
        .pipe(gulp.dest('dist'))
    });

    gulp-sourcemaps

    在现代javascript开发中, JavaScript脚本正变得越来越复杂。大部分源码(尤其是各种函数库和框架)都要经过转换,才能投入生产环境。
    常见的转换情况:

    • 压缩,减小体积。多个文件合并,减少HTTP请求数。其他语言编译成javascript。最常见的例子就是CoffeeScript。
      这三种情况,都使得实际运行的代码不同于开发代码,除错(debug)变得困难重重。
      Source map就是一个信息文件,里面储存着位置信息。也就是说,转换后的代码的每一个位置,所对应的转换前的位置。有了它,出错的时候,除错工具将直接显示原始代码,而不是转换后的代码。
      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'));
      });

      其它一些关注度高的gulp插件

      gulp-inject

      可以注入css,javascript和web组件,不需手工更新ndex.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'));
      });

      gulp-header

      为管道中的文件增加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插件。

      gulp-filter

      筛选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'));
      });

      gulp-changed

      只允许改变的文件通过管道。

      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));
      });

      gulp-bower

      执行bower安装。

      var gulp = require('gulp');
      var bower = require('gulp-bower');
      
      gulp.task('bower', function() {
        return bower()
          .pipe(gulp.dest('lib/'))
      });

      gulp-if

      有条件的执行任务

      gulp-replace

      字符串替换插件。

      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'));
      });

      gulp-shell

      可以执行shell命令

      gulp-exec

      exec插件

      gulp-install

      安装npm和bower包, 如果它们的配置文件存在的话。

      var install = require("gulp-install");
      
      gulp.src(__dirname + '/templates/**')
        .pipe(gulp.dest('./'))
        .pipe(install());

      gulp-rename

      改变管道中的文件名。

      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

      gulp-ignore

      忽略管道中的部分文件。

      gulp-util

      提供一些辅助方法。

      gulp-clean

      提供clean功能。

      var gulp = require('gulp');  
      var clean = require('gulp-clean');
      
      gulp.task('clean', function () {  
        return gulp.src('build', {read: false})
          .pipe(clean());
      });

      gulp-concat

      连接合并文件。

      var concat = require('gulp-concat');
      
      gulp.task('scripts', function() {
        gulp.src('./lib/*.js')
          .pipe(concat('all.js'))
          .pipe(gulp.dest('./dist/'))
      });

      gulp-wrap

      将一个lodash模版包装成流内容。

      gulp-declare

      安全的声明命名空间,设置属性。

      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/'));
      });

Tags:GU UL LP P插 
作者:网络 来源:miniApps的博
  • 上一篇:es6语法-3
  • 下一篇:String对象方法