当前位置: 首页 > 工具软件 > clean-css > 使用案例 >

gulp插件:gulp-cssnano,gulp-minify-css 和gulp-clean-css

子车鸿运
2023-12-01

近日在学习《Web前端自动化构建》,关于gulp的css压缩插件,书中先后提到了两个,分别是gulp-cssnano和gulp-minify-css,而执行npm install gulp-minify-css –save-dev时,控制台提示如下:
npm WARN deprecated gulp-minify-css@1.2.4: Please use gulp-clean-css
gulp-minify-css@1.2.4

至此,一共出现了三个压缩css的gulp插件。

对比如下

压缩能力:

相同css文件分别用这三个插件进行压缩,

  • gulp-cssnano:2.55KB;
  • gulp-minify-css: 2.44KB;
  • gulp-clean-css: 2.55KB;
维护:
使用:

鉴于gulp-minify-css已被废弃,在此仅对比gulp-cssnano和gulp-clean-css
gulp-cssnano
安装:

npm install gulp-cssnano --save-dev

示例:

const gulp = require('gulp');
const cssnano = require('gulp-cssnano');

gulp.task('styles', () => {
    return gulp.src('./main.css')
        .pipe(cssnano())
        .pipe(gulp.dest('dist'));
});

Source Maps:

const gulp = require('gulp');
const cssnano = require('gulp-cssnano');
const sourcemaps = require('gulp-sourcemaps');

gulp.task('styles', () => {
    return gulp.src('main.css')
        .pipe(sourcemaps.init())
        .pipe(cssnano())
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest('dist'));
});

gulp-clean-css
安装:

npm install gulp-clean-css --save-dev

示例:

const gulp = require('gulp');
const cleanCSS = require('gulp-clean-css');

gulp.task('minify-css', () => {
  return gulp.src('styles/*.css')
    .pipe(cleanCSS({compatibility: 'ie8'}))
    .pipe(gulp.dest('dist'));
});

gulp-clean-css支持回调函数

const gulp = require('gulp');
const cleanCSS = require('gulp-clean-css');

gulp.task('minify-css', () => {
  return gulp.src('styles/*.css')
    .pipe(cleanCSS({debug: true}, (details) => {
      console.log(`${details.name}: ${details.stats.originalSize}`);
      console.log(`${details.name}: ${details.stats.minifiedSize}`);
    }))
  .pipe(gulp.dest('dist'));
});

示例代码中可以获取css压缩前后的stats信息,同时它也提供了file name以及path用于其他分析。
Source Maps:

const gulp = require('gulp');
const cleanCSS = require('gulp-clean-css');
const sourcemaps = require('gulp-sourcemaps');

gulp.task('minify-css',() => {
  return gulp.src('./src/*.css')
    .pipe(sourcemaps.init())
    .pipe(cleanCSS())
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('dist'));
});
 类似资料: