In actual projects, in addition to HTML, CSS, JS and other files, a lot of pictures are also used. Compressing pictures can reduce the size of the picture file and increase the page opening speed.

How to compress pictures

To use gulp to compress images, you can use the following two plugins:

  • gulp-imagemin: The compression rate is not obvious, it can handle a variety of image formats, and can introduce more third-party optimization plug-ins.
  • gulp-smushit: The compression rate is relatively large, and it can only handle JPG and PNG.

For example, all our pictures are compressed into the image folder under the dist directory. Below we use the gulp-imagemin plug-in to achieve picture compression. In the project, in addition to PNG and JPG format pictures, there may also be pictures in other formats.

Example:

First install the gulp-imagemin plugin, the command is as follows:

npm install --save-dev gulp-imagemin

After the plug-in is successfully installed, we can write code in the gulpfile.js file:

// 获取 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()
})

Run the gulp images command:


知否
221 声望177 粉丝

Skrike while the iron is hot.