gulp学习

gulp是什么

gulp是一个打包工具,通过配置gulpfile.js来实现,和grunt一样可以通过多个 任务(task)来完成打包。
gulp比grunt更加简单易学
gulp官网

开始使用

安装项目依赖

npm install gulp --save-dev

创建gulpfile.js

栗子

压缩js ,这个栗子 把jquery 压缩 并重命名script.js 输出到build文件夹中
gulp-util记录错误日志
执行命令

gulp script

const gulp = require('gulp'),
	uglify = require('gulp-uglify'), // 压缩文件
	rename = require('gulp-rename')  // 重命名
	
gulp.task('script', done => {
  gulp
    .src('./node_modules/jquery/dist/jquery.js')
    .pipe(uglify()) // 压缩
    .on('error', err => {
        gulpUtil.log(gulpUtil.colors.red('Error'), err.toString());
      })
    .pipe(rename('script.js')) // 重命名
    .pipe(gulp.dest('build')); // 输出到build 文件夹中
  done();
});

es6

yarn add babel-core -D
// 按照babel-core 7 否则报找不到babel-core
 yarn add gulp-babel@7 -D
const gulp = require('gulp'),
   uglify = require('gulp-uglify'), // 压缩文件
   rename = require('gulp-rename'),  // 重命名
   babel = require('gulp-babel')
   
gulp.task('script', done => {
 gulp
   .src('./node_modules/jquery/dist/jquery.js')
   .pipe(babel({ presets: ['es2015'] }))
   .pipe(uglify()) // 压缩
   .on('error', err => {
       gulpUtil.log(gulpUtil.colors.red('Error'), err.toString());
     })
   .pipe(rename('script.js')) // 重命名
   .pipe(gulp.dest('build')); // 输出到build 文件夹中
 done();
});

压缩html
执行命令

gulp html

const minifyHtml = require('gulp-minify-html')
gulp.task('html', done => {
  gulp
    .src('./index.html')
    .pipe(minifyHtml())
    .pipe(gulp.dest('build'));
  done();
});

压缩css
执行命令

gulp css

const minifyCss = require('gulp-minify-css')
gulp.task('css', done => {
  gulp
    .src('./index.css')
    .pipe(minifyCss())
    .pipe(gulp.dest('build'));
  done();
});

清理build文件夹
当我们打包时希望先将build文件夹情况,那我们就创建一个clean任务

const clean = require('gulp-clean'),
	checkDir = path => {
	  console.log(fs.existsSync(path));
	  return fs.existsSync(path);
	};
gulp.task('clean', d => {
  // 只有这个文件夹存在时才 clean,不然会报错
  if (checkDir('./build')) {
    gulp.src('./build/').pipe(clean());
  }
  d();
});

压缩成zip包

npm install --save-dev gulp-zip

const gulpZip = require('gulp-zip')
gulp.task('script', done => {
  gulp
    .src('./node_modules/jquery/dist/jquery.min.js')
    .pipe($.uglify())
    .pipe(rename('script.js'))
    .pipe(gulpZip('myWorld.zip'))
    .pipe(gulp.dest('build'));
  done();
});

按顺序执行这几个任务

// gulp3 可以这样写
gulp.task('default', ['clean','script','css', 'html'], ()=> {
     console.log('default')
})
// gulp4
```js
gulp.task('default', gulp.series('clean', 'script', 'css', 'html', done => done()))

实战

在日常的开发时 ,我们希望把index.html引用的js,css分别合并压缩成一个文件
gulp也提供了这种方法,通过识别index.html中的注释来实现
栗子
注释的意思是 ,构建注释中的css 并合并压缩到css/css.css中

<!-- build:css css/css.css -->
    <link rel="stylesheet" href="index.css" />
    <link
      rel="stylesheet"
      href="./node_modules/bootstrap/dist/css/bootstrap.min.css"
    />
    <!-- endbuild -->

构建注释中js,并并压缩到scripts/script.js中

<!-- build:js scripts/script.js -->
    <script src="./node_modules/jquery/dist/jquery.js"></script>
    <script src="./node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
    <script src="./app.js"></script>
    <script src="./js/snow.js"></script>
    <!-- endbuild -->

gulpfile.js 执行gulp 就可以完成打包啦

gulp

const gulp = require('gulp'),
  uglify = require('gulp-uglify'), // 压缩文件
  rename = require('gulp-rename'), // 重命名
  jshint = require('gulp-jshint'),
  minifyHtml = require('gulp-minify-html'),
  miniHtml = require('gulp-htmlmin'),
  minifyCss = require('gulp-minify-css'),
  imagemin = require('gulp-imagemin'),
  useref = require('gulp-useref'),
  csso = require('gulp-csso'),
  rev = require('gulp-rev'),
  revReplace = require('gulp-rev-replace'),
  filter = require('gulp-filter'),
  clean = require('gulp-clean'),
  fs = require('fs'),
  gulpIf = require('gulp-if'),
  gulpUtil = require('gulp-util'),
  babel = require('gulp-babel'),
  gulpZip = require('gulp-zip'),
  $ = require('gulp-load-plugins')();
// gulp.task('js', function () {
//     return gulp.src('dist/js/*.js').pipe(uglify())
// })

// gulp.src('./node_modules/**/*.js').pipe(uglify()).pipe(gulp.dest('build'))

//js代码的处理
// gulp.task('vendor', function () {
//     return gulp.src('./node_modules/**')
//         .pipe(uglify())
//         .pipe(rename('index.min.js'))
//         .pipe(gulp.dest('build'))
// });
//js代码的处理
gulp.task('script', done => {
  gulp
    .src('./node_modules/jquery/dist/jquery.min.js')
    .pipe($.uglify())
    .pipe(rename('script.js'))
    .pipe(gulp.dest('build'));
  done();
});

// [20:08:56] The following tasks did not complete: default, script
// [20:08:56] Did you forget to signal async completion?
// gulp.task('css', function () {
//     gulp.src('')
// })

// gulp.task('html', function () {
//     gulp.src('./index.html')
//         .pipe(minifyHtml())
//         .pipe(gulp.dest('build'))
// })

gulp.task('html', done => {
  gulp
    .src('./index.html')
    .pipe(minifyHtml())
    .pipe(gulp.dest('build'));
  done();
});

gulp.task('css', done => {
  gulp
    .src('./index.css')
    .pipe(minifyCss())
    .pipe(gulp.dest('build'));
  done();
});

gulp.task('image', done => {
  gulp
    .src('./img/**')
    .pipe(
      imagemin({
        progressive: true,
        interlaced: true
      })
    )
    .pipe(gulp.dest('build/img'));
  done();
});

gulp.task('font', done => {
  gulp.src('./css/font/**').pipe(gulp.dest('build/css/font'));
  done();
});

const checkDir = path => {
  console.log(fs.existsSync(path));
  return fs.existsSync(path);
};

// gulp3 可以 gulp4 不可以
// gulp.task('default', ['script', 'html'], function () {
//     console.log('default')
// })
// gulp.task('default', gulp.series('script', 'html', 'image', done => done()))
gulp.task('clean', d => {
  if (checkDir('./build')) {
    gulp.src('./build/').pipe(clean());
  }
  d();
});

gulp.task(
  'default',
  gulp.series('clean', 'font', 'image', done => {
    const jsFilter = filter('**/*.js', {
        restore: true
      }),
      cssFilter = filter('**/*.css', {
        restore: true
      }),
      // 第一个参数代表所有 第二个参数代表除了index.html
      indexHtmlFilter = filter(['**/*', '!index.html'], {
        restore: true
      });

    // pump

    gulp
      .src('index.html')
      .pipe($.useref()) /**找到注释 */
      .pipe(jsFilter) /**筛选js */
      .pipe(babel({ presets: ['es2015'], compact: false }))
      .pipe(uglify()) /**压缩js */
      .on('error', err => {
        gulpUtil.log(gulpUtil.colors.red('Error'), err.toString());
      })
      .pipe(jsFilter.restore) /** 把js文件扔回流里 */
      .pipe(cssFilter)
      // .pipe(minifyCss())
      .pipe(csso())
      .pipe(cssFilter.restore)
      .pipe(indexHtmlFilter)
      .pipe(
        rev()
      ) /**前面的filter排除了index.html 然后再打版本号  gulp-rev 为静态文件随机添加hash值 */
      .pipe(indexHtmlFilter.restore)
      .pipe(revReplace()) /**更新index中的引用 */
      // .pipe(minifyHtml()) // 压缩后 js报错
      // .pipe(miniHtml({ removeComments: true }))
      .pipe(gulp.dest('build'))
      .pipe(gulpZip('myWorld.zip'))
      .pipe(gulp.dest('build'));
    done();
  })
);




gulp-load-plugins

可以更简单的应用gulp的插件

const $ = require('gulp-load-plugins')();
gulp.task('script', done => {
  gulp
    .src('./node_modules/jquery/dist/jquery.min.js')
//    .pipe(uglify()) // 原来的写法
    .pipe($.uglify())
    .pipe(rename('script.js'))
    .pipe(gulp.dest('build'));
  done();
});

常见的问题

  • 执行代码检查时的问题
Error: Cannot find module 'jshint/src/cli'

npm install --save-dev gulp-jshint
npm install --save-dev jshint

  • 顺序执行任务时的问题
 AssertionError [ERR_ASSERTION]: Task function must be specified

https://blog.csdn.net/JsongNeu/article/details/89284959

  • gulp异步问题
 Did you forget to signal async completion?

问题console

PS E:\Practice\myWorld> gulp script
[09:49:23] Using gulpfile E:\Practice\myWorld\gulpfile.js
[09:49:23] Starting 'script'...
[09:49:24] The following tasks did not complete: script
[09:49:24] Did you forget to signal async completion?

问题代码

gulp.task('script', () => {
  gulp
    .src('./node_modules/jquery/dist/jquery.min.js')
    .pipe($.uglify())
    .pipe(rename('script.js'))
    .pipe(gulp.dest('build'));
  // done();
});

正确代码

gulp.task('script', done => {
  gulp
    .src('./node_modules/jquery/dist/jquery.min.js')
    .pipe($.uglify())
    .pipe(rename('script.js'))
    .pipe(gulp.dest('build'));
  done();
});
  • [BABEL] Note: The code generator has deoptimised the styling of “E:/Practice/myWorld/scripts/three.js” as it exceeds the max of “500KB”.
    compact设为false
.pipe(babel({ presets: ['es2015'], compact: false }))
gulp
      .src('index.html')
      .pipe($.useref()) /**找到注释 */
      .pipe(jsFilter) /**筛选js */
      .pipe(babel({ presets: ['es2015'], compact: false }))
      .pipe(uglify()) /**压缩js */
      .on('error', err => {
        gulpUtil.log(gulpUtil.colors.red('Error'), err.toString());
      })

20190524更新
gulp 打包过的文件如果没有改动,下次再打包时不会重新打包

gulp打包时报错 Error: ENOENT: no such file or directory, chmod ‘E:\Practice\myWorld\build\img\bg’

PS E:\Practice\myWorld> gulp
[13:41:56] Using gulpfile E:\Practice\myWorld\gulpfile.js
[13:41:56] Starting 'default'...
[13:41:56] Starting 'clean'...
true
[13:41:56] Finished 'clean' after 6.39 ms
[13:41:56] Starting 'font'...
d
[13:41:56] Finished 'font' after 10 ms
[13:41:56] Starting 'image'...
[13:41:56] Finished 'image' after 3.97 ms
[13:41:56] Starting 'hero'...
[13:41:56] Finished 'hero' after 3.15 ms
[13:41:56] Starting '<anonymous>'...
[13:41:56] Finished '<anonymous>' after 6.04 ms
[13:41:56] Finished 'default' after 37 ms
events.js:174
      throw er; // Unhandled 'error' event
      ^

Error: ENOENT: no such file or directory, chmod 'E:\Practice\myWorld\build\img\bg'
Emitted 'error' event at:
    at Pumpify.EventEmitter.emit (domain.js:454:12)
    at Pumpify.onerror (E:\Practice\myWorld\node_modules\readable-stream\lib\_stream_readable.js:640:52)
    at Pumpify.emit (events.js:189:13)
    at Pumpify.EventEmitter.emit (domain.js:441:20)
    at Pumpify.Duplexify._destroy (E:\Practice\myWorld\node_modules\duplexify\index.js:191:15)
    at E:\Practice\myWorld\node_modules\duplexify\index.js:182:10
    at process._tickCallback (internal/process/next_tick.js:61:11)
    

参考
https://blog.csdn.net/JsongNeu/article/details/90515468

20190531更新

gulp任务分散到不同的文件中

当任务比较多的是时候,会有一个比较长的gulpfile.js,为了方便维护,我们可以把gulpfile的任务拆分成多个多文件,一个文件中包含一个任务

新建一个gulpfile.js,用于引用gulp任务。
新建task文件夹,用于存放gulp任务

需要用到的插件require-dir

npm install -D require-dir

文件目录


gulpfile.js
task/
|—uglify.js


const requireDir = require(‘require-dir’),
dir = requireDir(’./task’);

gulpfile.js

const requireDir = require('require-dir'),
  gulp = require('gulp'),
  dir = requireDir('./task');

gulp.task('default', gulp.series('script'));

task/uglify.js

const gulp = require('gulp'),
  uglify = require('gulp-uglify'),
  rename = require('gulp-rename'),
  babel = require('gulp-babel');

gulp.task('script', done => {
  // 打包es6 一定要用babel  不然报错
  gulp
    .src('es6.js')
    .pipe(babel({ presets: ['es2015'] }))
    .pipe(uglify())
    .pipe(rename('script.js'))
    .pipe(gulp.dest('build'));

  done();
});

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值