近日在学习《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文件分别用这三个插件进行压缩,
current tags: 2.1.3 Published 4 months ago
; 1.2.4 Published 2 years ago Please use gulp-clean-css
; 3.9.4 Published 2 months ago
; 鉴于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'));
});