5

Gulp 使用gulp压缩图片

 3 years ago
source link: https://segmentfault.com/a/1190000040022772
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Gulp 使用gulp压缩图片

在实际项目中,除了 HTML、CSS、JS 等文件,还会用到大量的图片。压缩图片可降低图片文件大小,提高页面打开速度。

如何压缩图片

使用 gulp 来压缩图片可以使用下面两个插件:

  • gulp-imagemin:压缩率不明显,可以处理多种图片格式,可以引入更多第三方优化插件。
  • gulp-smushit:压缩率比较大,只能处理 JPG 和 PNG。

例如我们所有的图片压缩到 dist 目录下的 image 文件夹中,下面我们使用 gulp-imagemin 插件来实现图片的压缩,在项目中,除了 PNG 和 JPG 格式的图片,也有可能有其他格式的图片。

首先安装 gulp-imagemin 插件,命令如下所示:

npm install --save-dev gulp-imagemin

插件安装成功后,我们就可以在 gulpfile.js 文件中编写代码:

// 获取 gulp
var gulp = require('gulp')
// 获取 uglify 模块
var imagemin = require('gulp-imagemin')
// 压缩图片任务
gulp.task('images', function(cb) {
    // 找到图片
    gulp.src('image/*')
        .pipe(imagemin({
            progressive: true,
        }))
        .pipe(gulp.dest('dist/image'))
        cb()
})

运行 gulp images 命令:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK