【干货】一篇文章学会Gulp(Getting started with Gulp)

抛开Grunt,又有一个新的自动化构建系统成为新的领跑者。那就是Gulp。

Gulp是一种直观、自动化构建的工具。

为什么前端er会这么感兴趣Gulp?我相信大家都有个思想:要么不做事,要做事就要把事情做得最好!

Gulp就是帮你把前端的事情做好的一个工具!Gulp是基于Node和NPM,安装教程点这里

什么是Gulp?

Gulp使用了node.js的流控制系统,使其(Gulp)构建更快,因为它不需要将临时文件/文件夹写入磁盘。

如果你想了解更多关于流控制系统——这不是必需的——这篇文章页是很值得推荐你们去看的。

Gulp允许你去指定你的源文件是哪些,然后用管道的方式传输你的源文件到一堆的插件中进行编译,最后得出你想要的结果,这比Grunt的设置每个插件的输入输出的繁琐操作简单多了。

管道流操作:

我们要修改编译、合并或者压缩的文件都放在一起,然后通过管道流,管道流里面含有多种的插件,这些插件会按照你指定的操作顺序的方法进行对文件的操作,操作过后生成新的目标文件。

如出现下列错误:

Error: Cannot find module 'jshint/src/cli

我认为开发人员在最新版本中改变了gulp-jshint的结构导致了这个问题,解决问题的办法:

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

举一个相同的例子对比一下Grunt和Gulp(Sass编译):

Grunt:

sass: {
  dist: {
    options: {
      style: 'expanded'
    },
    files: {
      'dist/assets/css/main.css': 'src/styles/main.scss',
    }
  }
},

autoprefixer: {
  dist: {
    options: {
      browsers: [
        'last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'
      ]
    },
    src: 'dist/assets/css/main.css',
    dest: 'dist/assets/css/main.css'
  }
},

grunt.registerTask('styles', ['sass', 'autoprefixer']);

Grunt需要单独配置每一个插件,为每个插件指定源文件和结果输出的路径。(贼麻烦好吗。)

例如:我们输入一个文件到Sass编译的插件里,然后保存输出。在这之后我们还要配置Autoprefixer来输入Sass的输出,然后输出另一个文件。让我们看一看同样的配置在Gulp下是怎么做的吧:

Gulp:

gulp.task('sass', function() {
  return sass('src/styles/main.scss', { style: 'expanded' })
       .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
       .pipe(gulp.dest('dist/assets/css'))
});

在Gulp下我们只需要配置一个文件。这是由Sass插件修改的,传递给Autoprefixer插件修改,最后我们得到一个文件。这个过程加快的构建过程,因为我们不需要阅读和编写不必要的文件。

 

现在你已经基本了解Gulp了,现在来安装Gulp和开始创建一些例子吧!

安装Gulp:

在我们配置文件之前,我们需要全局安装gulp:

$ npm install gulp -g

在这里我们是要全局安装gulp,因为我们需要给权限到gulp的CLI上。安装完成后我们需要进入到我们的项目根目录下。

$ cd XXX
$ npm install gulp --save-dev

运行完这两条命令我们在package.json中的devDependencies看到了有gulp。

安装gulp插件:

我们将安装一些的插件来完成以下的任务:

运行以下命令安装这些插件(建议用cnpm,插件太多):

$ npm install gulp-ruby-sass gulp-autoprefixer gulp-cssnano gulp-jshint gulp-concat gulp-uglify gulp-imagemin gulp-notify gulp-rename gulp-cache gulp-livereload del --save-dev

这条命令将会安装所有必须的插件和保存在package.json的devDependencies中。更多的插件在这里

引入插件:

下一步,我们需要创建一个gulpfile.js文件和引入插件:

var gulp = require('gulp'),
    sass = require('gulp-ruby-sass'),
    cssnano = require('gulp-cssnano'),
autoprefixer = require('gulp-autoprefixer'); jshint
= require('gulp-jshint'), uglify = require('gulp-uglify'), imagemin = require('gulp-imagemin'),
rename = require('gulp-rename'), concat = require('gulp-concat'),
cache = require('gulp-cache'), notify
= require('gulp-notify'), livereload = require('gulp-livereload'), del = require('del');

Gulp插件与Grunt插件有一点不同——它们被设计成只可以做一件事和这件事一定要做到最好。

来个示例;Grunt的imagemin使用缓存,以避免压缩已经压缩的图像。对于gulp,这将用一个缓存插件来完成,它也可以用来缓存其他的东西。这为构建过程增加了额外的灵活性。

其实我们可以像Grunt一样使用自动加载所有已安装的插件,但为了这篇文章的目的,我们将坚持手动方法。

创建任务:

编译和压缩Sass:

首先,我们将配置Sass编译。我们将编译Sass作为扩展,通过自动修复程序运行它并将它保存到我们的目的地。然后我们会创建一个小型的:min版本,自动刷新页面并通知任务已经完成。是不是贼酷?

gulp.task('styles', function() {
  return sass('src/styles/main.scss', { style: 'expanded' })
    .pipe(autoprefixer('last 2 version'))
    .pipe(gulp.dest('dist/assets/css'))
    .pipe(rename({suffix: '.min'}))
    .pipe(cssnano())
    .pipe(gulp.dest('dist/assets/css'))
    .pipe(notify({ message: 'styles任务完成' }));
});

在这里再做点解释再往前走。

gulp.task('styles', function() { ... )};

这个gulp.task是用来创建gulp任务的API。上面可以用 $ gulp styles 从终端运行。

return sass('src/styles/main.scss', { style: 'expanded' })

这是gulp-ruby-sass的API,我们定义源文件并传递任何选项。对于很多其他插件,你可以使用gulp.src的API来控制文件。比如:*.scss可以匹配所有以.scss为结尾的文件。通过返回流控制系统使他具有异步性,在我们收到通知之前,确保任务已经完成。

.pipe(autoprefixer('last 2 version'))

我们用.pipe()通过管道传输方式把源文件传输到插件上。通常各种插件的选项是在他们各自的GitHub页面上找到的。为了方便起见,我把它们连在一起了。管道是可链接的,因此您可以在流控制系统中添加尽可能多的插件。

.pipe(gulp.dest('dist/assets/css'));

gulp.dest的API为我们设定最终输出文件的位置。一个任务可以有多个目的地,一个可以输出扩展版本,另一个可以输出压缩版本。这在上面的styles任务中演示。

我建议去看看gulp的API文档,以更好地了解这些方法。英文文档其实看起来也没那么吓人!

代码规范+合并+压缩JavaScript:

通过以上解释我希望你们能掌握怎么使用gulp了,接下来我们把脚本任务设为规范+合并+压缩:

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/assets/js'))
    .pipe(rename({suffix: '.min'}))
    .pipe(uglify())
    .pipe(gulp.dest('dist/assets/js'))
    .pipe(notify({ message: 'Scripts任务完成' }));
});

在这里我们通过gulp.src的API把我们要修改的文件放到管道流中。详细流程见下图(如看不清鼠标右键->在新标签页中打开图片):

 

压缩图片:

gulp.task('images', function() {
  return gulp.src('src/images/**/*')
    .pipe(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true }))
    .pipe(gulp.dest('dist/assets/img'))
    .pipe(notify({ message: 'Images任务完成' }));
});

这个任务会把images文件夹下的所有图片文件通过imagemin插件进行图片压缩。我们可以更进一步,利用缓存来保存在每次运行这个任务时已经压缩的图像。我们需要的是之前安装的gulp - cache插件。设置这个,我们需要去改变这一行的:

.pipe(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true }))

改成

.pipe(cache(imagemin({ optimizationLevel: 5, progressive: true, interlaced: true })))

现在只有新的或改变的图像将被压缩。

清除文件:

在部署之前,清理目标文件夹并重新构建文件是一个好主意——以防任何已经从源文件中删除,并在目标文件夹中挂起(例子:空文件夹):

gulp.task('clean', function() {
    return del(['dist/assets/css', 'dist/assets/js', 'dist/assets/img']);
});

在这里我们不需要使用gulp插件,因为我们可以在gulp中直接利用节点模块。我们使用返回来确保任务在退出前完成。

默认任务:

我们也可以创建一个默认任务,可以在命令行中直接 $ gulp 就可以使用,下面的例子就是运行我们已经创建好的三个任务:

gulp.task('default', function() {
    gulp.start('styles', 'scripts', 'images');
});

注意在gulp . task中附加的数组。在这里,我们可以定义任务依赖项。在这个示例中,clean任务将在任务开始之前运行。在Gulp中,任务同时运行,没有顺序完成,所以我们需要确保在运行额外任务之前完成clean的任务。

监测任务:

为了查看我们的文件并在它们发生变化时执行必要的任务,我们首先需要创建一个新任务,然后使用gulp.watch的API监测文件:

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

});

当我们运行 $ gulp task 的时候它就会自动监测这些文件。

实时刷新:

gulp也可以在游览器上监测文件变化实时刷新页面,不过在这里需要游览器安装插件。另外我会专门写个博客是专对于gulp的实时刷新:

gulp.task('watch', function() {

  // Create LiveReload server
  livereload.listen();

  // Watch any files in dist/, reload on change
  gulp.watch(['dist/**']).on('change', livereload.changed);

});

为了能让任务能执行,你要在游览器中安装LiveReload插件

把所有任务集合在一起:

在这里我收集了我平时需要的所有gulp插件:GitHub地址

 

以上。

转载于:https://www.cnblogs.com/scottjeremy/p/7264056.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Getting Started with Gulp - Second Edition by Travis Maynard English | 28 Apr. 2017 | ASIN: B071DB5ML8 | 132 Pages | AZW3 | 4.23 MB Key Features Gain a solid understanding of Gulp and write your own custom tasks from scratch Discover ways to add additional functionality to improve your tasks Get up-and-running with new features added to the latest version of Gulp Book Description This book is a hands-on guide to get you up to speed with gulp. You will quickly learn how to install, configure, and run your own build system. It will instill you with the ability to automate several common development tasks to vastly improve your development workflow. This book first demonstrates various Gulp use cases before running through the steps of configuring, running, and customizing Gulp, providing you with core concepts of gulp, node.js, and npm. Diving a bit deeper into the gulp ecosystem, we will discuss when and why to use a node module instead of a gulp plugin. We will also go over a few issues that we can run into while using gulp and learn about ways to work around them to improve your gulp experience. By the end of this book, you will be able to create your very own gulp build from scratch, create and maintain tasks and project builds, and automate your workflow with plugins and custom tasks. What you will learn How to use a command-line interface. Learn about Gulp, Node.js, and npm and how they work together. Create a Gulpfile from scratch and implement it into a project. Write basic tasks that will concatenate, minify, compress, and pre-process your files. Write advanced tasks that will run a local server, sync file changes to your browser, and allow you to write client-side JavaScript using ES2015. About the Author Travis Maynard is a software engineer who focuses on minimalism and simplicity. He is currently creating software at JazzHR to help growing companies find and hire great employees. Prior to his work at JazzHR, he designed web frameworks and user experiences at West Virginia University to serve their education and marketing efforts. In his spare time, he actively contributes to the open source software community and occasionally writes about the Web. Table of Contents Introducing Gulp Getting Started Understanding the Basics of Gulp Performing Tasks with Gulp Creating Advanced Tasks Tips, Tricks, and Resolving Issues
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值