Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

精通 gulp 常用插件的功能和用法 #2

Open
lin-xin opened this issue Mar 9, 2017 · 23 comments
Open

精通 gulp 常用插件的功能和用法 #2

lin-xin opened this issue Mar 9, 2017 · 23 comments
Labels

Comments

@lin-xin
Copy link
Owner

@lin-xin lin-xin commented Mar 9, 2017

gulp的官方定义非常简洁: 基于文件流的构建系统 。通过代码优于配置的策略,Gulp 让简单的任务简单,复杂的任务可管理。利用 Node.js 流的威力,你可以快速构建项目并减少频繁的 IO 操作。Gulp 严格的插件指南确保插件如你期望的那样简洁高质得工作。

匹配符 *、**、!、{}

src('./js/*.js')               // * 匹配js文件夹下所有.js格式的文件
src('./js/**/*.js')            // ** 匹配js文件夹的0个或多个子文件夹
src(['./js/*.js','!./js/index.js'])    // ! 匹配除了index.js之外的所有js文件
src('./js/**/{omui,common}.js')        // {} 匹配{}里的文件名

文件操作

del (替代gulp-clean)

const del = require('del');

del('./dist');                      // 删除整个dist文件夹

gulp-rename

描述:重命名文件。

const { src, dest } = require('gulp');
const rename = require("gulp-rename");

const renameTask = cb => {
    src('./hello.txt')
        .pipe(rename('gb/goodbye.md'))    // 直接修改文件名和路径
        .pipe(dest('./dist')); 
    cb();
}
const optionTask = cb => {
    src('./hello.txt')
        .pipe(rename({
            dirname: "text",                // 路径名
            basename: "goodbye",            // 主文件名
            prefix: "pre-",                 // 前缀
            suffix: "-min",                 // 后缀
            extname: ".html"                // 扩展名
        }))
        .pipe(dest('./dist'));
    cb();
}

gulp-concat

描述:合并文件。

const { src, dest } = require('gulp');
const concat = require('gulp-concat');

const concatTask = cb => {
    src('./js/*.js')
        .pipe(concat('all.js'))         // 合并all.js文件
        .pipe(dest('./dist'));
    cb();
}

gulp-filter

描述:在虚拟文件流中过滤文件。

const { src, dest } = require('gulp');
const filter = require('gulp-filter');

const f = filter(['**', '!*/index.js']);
const fTask = cb => {
    src('js/**/*.js')
        .pipe(f)                        // 过滤掉index.js这个文件
        .pipe(dest('dist'));
    cb();
}

const f1 = filter(['**', '!*/index.js'], {restore: true});
const f1Task = cb => {
    src('js/**/*.js')
        .pipe(f1)                       // 过滤掉index.js这个文件
        .pipe(uglify())                 // 对其他文件进行压缩
        .pipe(f1.restore)               // 返回到未过滤执行的所有文件
        .pipe(dest('dist'));       // 再对所有文件操作,包括index.js
    cb();
}

压缩

gulp-uglify

描述:压缩js文件大小。

const { src, dest } = require('gulp');
const uglify = require("gulp-uglify");

const uglifypTask = cb => {
    src('./hello.js')
        .pipe(uglify())                 // 直接压缩hello.js
        .pipe(dest('./dist'))
    cb();
}

const optionpTask = cb => {
    src('./hello.js')
        .pipe(uglify({
            mangle: true,               // 是否修改变量名,默认为 true
            compress: true,             // 是否完全压缩,默认为 true
            preserveComments: 'all'     // 保留所有注释
        }))
        .pipe(dest('./dist'))
    cb();
}

gulp-csso

描述:压缩优化css。

const { src, dest } = require('gulp');
const csso = require('gulp-csso');

const cssopTask = cb => {
    src('./css/*.css')
        .pipe(csso())
        .pipe(dest('./dist/css'))
    cb();
}

gulp-html-minify

描述:压缩HTML。

const { src, dest } = require('gulp');
const htmlmini = require('gulp-htmlmin');

const minpTask = cb => {
    src('index.html')
        .pipe(htmlmini())
        .pipe(dest('./dist'))
    cb();
}

gulp-imagemin

描述:压缩图片。

const { src, dest } = require('gulp');
const imagemin = require('gulp-imagemin');

const minpTask = cb => {
    src('./img/*.{jpg,png,gif,ico}')
        .pipe(imagemin())
        .pipe(dest('./dist/img'))
    cb();
}

gulp-zip

描述:ZIP压缩文件。

const { src, dest } = require('gulp');
const zip = require('gulp-zip');

const zipTask = cb => {
    src('./src/*')
        .pipe(zip('all.zip'))                   // 压缩成all.zip文件
        .pipe(dest('./dist'))
    cb();
}

JS/CSS自动注入

gulp-autoprefixer

描述:自动为css添加浏览器前缀。

const { src, dest } = require('gulp');
const autoprefixer = require('gulp-autoprefixer');

const prefTask = cb => {
    src('./css/*.css')
        .pipe(autoprefixer())           // 直接添加前缀
        .pipe(dest('dist'))
    cb();
}
const optionTask = cb => {
    src('./css/*.css')
        .pipe(autoprefixer({
            browsers: ['last 2 versions'],      // 浏览器版本
            cascade:true                       // 美化属性,默认true
            add: true                           // 是否添加前缀,默认true
            remove: true                        // 删除过时前缀,默认true
            flexbox: true                       // 为flexbox属性添加前缀,默认true
        }))
        .pipe(dest('./dist'))
    cb();
}

查看更多配置:options

更多浏览器版本:browsers

gulp-useref

描述:解析构建块在HTML文件来代替引用未经优化的脚本和样式表。

<!-- index.html -->
<!-- build:css /css/all.css -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<!-- endbuild -->
// gulpfile.js
const { src, dest } = require('gulp');
const useref = require('gulp-useref');
const userefTask = cb => {
    src('index.html')
        .pipe(useref())
        .pipe(dest('./dist'))
    cb();
}

替换之后的index.html中就会变成:

<link rel="stylesheet" href="css/all.css">  // 之前的两个<link>替换成一个了

gulp-rev

描述:给静态资源文件名添加hash值:unicorn.css => unicorn-d41d8cd98f.css

const { src, dest } = require('gulp');
const rev = require('gulp-rev');

const revTask = cb => {
    src('./css/*.css')
        .pipe(rev())
        .pipe(dest('./dist/css'))
    cb();
}

gulp-rev-replace

描述:重写被gulp-rev重命名的文件名。

const { src, dest } = require('gulp');
const rev = require('gulp-rev');
const revReplace = require('gulp-rev-replace');
const useref = require('gulp-useref');

const revReplaceTask = cb => {
    src('index.html')
        .pipe(useref())                         // 替换HTML中引用的css和js
        .pipe(rev())                            // 给css,js,html加上hash版本号
        .pipe(revReplace())                     // 把引用的css和js替换成有版本号的名字
        .pipe(dest('./dist'))
    cb();
}

gulp-html-replace

描述:替换html中的构建块。

<!-- index.html -->

<!-- build:css -->                          // css是buildName,可以自己定义
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<!-- endbuild -->
// gulpfile.js
const { src, dest } = require('gulp');
const htmlreplace = require('gulp-html-replace');

const replaceTask = cb => {
    src('index.html')
        .pipe(htmlreplace({
            'css':'all.css'                     // css是index.html中定义的buildName
        }))
        .pipe(dest('./dist'))
    cb();
}

替换之后的index.html中就会变成:

    <link rel="stylesheet" href="all.css">      <!-- 之前的两个<link>替换成一个了 -->

流控制

gulp-if

描述:有条件地运行一个任务。

const { src, dest } = require('gulp');
const gulpif = require('gulp-if');
const uglify = require('gulp-uglify');
const concat = require('gulp-concat');
const condition = true; 

const ifTask = cb => {
    src('./js/*.js')
        .pipe(gulpif(condition, uglify(), concat('all.js')))  // condition为true时执行uglify(), else 执行concat('all.js')
        .pipe(dest('./dist/'));
    cb();
}

工具

gulp-load-plugins

描述:从包的依赖和附件里加载gulp插件到一个对象里给你选择。

// package.json 

"devDependencies": {
    "gulp": "^3.9.1",
    "gulp-concat": "^2.6.1",
    "gulp-rename": "^1.2.2",
    "gulp-uglify": "^2.0.1"
}

// gulpfile.js
const { src, dest } = require('gulp');
const $ = require('gulp-load-plugins')();     // $ 是一个对象,加载了依赖里的插件

const minTask = cb => {
    src('./**/*.js')
        .pipe($.concat('all.js'))               // 使用插件就可以用$.PluginsName()
        .pipe($.uglify())
        .pipe($.rename('all.min.js'))
        .pipe(dest('./dist'))
    cb();
}

gulp-sass

描述:编译sass。

const { src, dest, watch } = require('gulp');
const sass = require('gulp-sass');

const sassTask = cb => {
    src('./sass/**/*.scss')
        .pipe(sass({
            outputStyle: 'compressed'           // 配置输出方式,默认为nested
        }))
        .pipe(dest('./dist/css'));
    cb();
}
watch('./sass/**/*.scss', sassTask);   // 实时监听sass文件变动,执行sass任务

gulp-babel

描述:将ES6代码编译成ES5。

const { src, dest } = require('gulp');
const babel = require('gulp-babel');

const jsTask = cb => {
    src('./js/index.js')
        .pipe(babel({
            presets: ['@babel/env'],
            sourceType: 'script'
        }))
        .pipe(dest('./dist'))
    cb();
}
@lin-xin lin-xin added the gulp label Mar 9, 2017
@jweboy
Copy link

@jweboy jweboy commented Apr 26, 2017

Mark

1 similar comment
@XiomgMingCai
Copy link

@XiomgMingCai XiomgMingCai commented May 15, 2017

Mark

@yang123guo
Copy link

@yang123guo yang123guo commented Jul 14, 2017

mark an use it

@Mengkzhaoyun
Copy link

@Mengkzhaoyun Mengkzhaoyun commented Jul 28, 2017

Mark

1 similar comment
@NewPrototype
Copy link

@NewPrototype NewPrototype commented Aug 22, 2017

Mark

@Maplesog
Copy link

@Maplesog Maplesog commented Aug 30, 2017

M

2 similar comments
@MagicHacker
Copy link

@MagicHacker MagicHacker commented Oct 30, 2017

M

@yanxiaochuan
Copy link

@yanxiaochuan yanxiaochuan commented Dec 1, 2017

M

@hpboys
Copy link

@hpboys hpboys commented Dec 13, 2017

Mark

@lin-xin lin-xin added the web tools label Dec 28, 2017
@wbbhacker
Copy link

@wbbhacker wbbhacker commented Jan 2, 2018

M

@GunSnake
Copy link

@GunSnake GunSnake commented Jan 19, 2018

Mark

@mrgu1609
Copy link

@mrgu1609 mrgu1609 commented Jan 30, 2018

mark

@catboy1006
Copy link

@catboy1006 catboy1006 commented Apr 27, 2018

m

@wuyf123
Copy link

@wuyf123 wuyf123 commented Jun 22, 2018

mark

1 similar comment
@JangYB
Copy link

@JangYB JangYB commented Jun 28, 2018

mark

@linfeimy
Copy link

@linfeimy linfeimy commented Jul 16, 2018

Mark!

@unclemeric
Copy link

@unclemeric unclemeric commented Jul 27, 2018

mark

1 similar comment
@ewillgo
Copy link

@ewillgo ewillgo commented Aug 4, 2018

mark

@zhangji1992
Copy link

@zhangji1992 zhangji1992 commented Aug 20, 2018

thx.It helps a lot.

@tinyking
Copy link

@tinyking tinyking commented Jul 3, 2019

thx

@bibichuan
Copy link

@bibichuan bibichuan commented Aug 8, 2019

const f = filter(['**', '!*/pagination.js'], {restore: true}); gulp.task('minify-js', function() { return gulp.src('./public/**/*.js') // .pipe(babel({presets: ['env']})) .pipe(f) .pipe(uglify()) .pipe(gulp.dest('./public')); });我想把public文件夹中的pagination.js过滤掉,但是这样写,pagination.js还是会被处理和压缩,这是什么原因呢?和windows系统有关系吗?
gulp-filter_1

@touxing
Copy link

@touxing touxing commented Sep 11, 2019

const f = filter(['**', '!*/pagination.js'], {restore: true}); gulp.task('minify-js', function() { return gulp.src('./public/**/*.js') // .pipe(babel({presets: ['env']})) .pipe(f) .pipe(uglify()) .pipe(gulp.dest('./public')); });我想把public文件夹中的pagination.js过滤掉,但是这样写,pagination.js还是会被处理和压缩,这是什么原因呢?和windows系统有关系吗?
gulp-filter_1

读取js和压缩后的js文件放在同一个目录可能会存在问题

你可以这样写

gulp.task('minify-js', function() {
  return gulp.src(['./public/**/*.js', '!./public/**/pagination.js'])
                    .pipe(uglify())
                    .pipe(gulp.dest('./otherFolder'))

})
@bibichuan
Copy link

@bibichuan bibichuan commented Sep 11, 2019

谢谢 @touxing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
You can’t perform that action at this time.