1

In addition to using gulp compress the JS file, CSS . Compressing the CSS code can reduce CSS file and increase the opening speed of the web page.

Compress CSS files

Use gulp to compress CSS procedure files and compressed JS file almost in front of us learned how to compress JS file, then re-learning compressed CSS file will feel very simple matter.

Compression CSS files also need to use the appropriate plug on gulp of CSS compression plug-ins, a total of three as follows:

  • gulp-cssnano
  • gulp-minify-css
  • gulp-clean-css

The above three plug-ins, because gulp-minify-css now been marked as deprecated , because we can use the remaining two plug-ins.

For example, all our .css files are compressed into the dist folder under the css directory. The specific operations are as follows.

Install plugin

First install the gulp-clean-css plug-in, the command is as follows:

npm install gulp-clean-css

As shown below:

Write the code in the gulpfile.js file

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

Example:
// 获取 gulp
var gulp = require('gulp')
var cleancss = require('gulp-clean-css')
gulp.task('testcss', function(cb) {
    gulp.src('css/*.css')
        .pipe(cleancss())
        .pipe(gulp.dest('dist/css'))
        cb()
})

Run the gulp testcss command to compress the CSS file:

At this point in the project root directory dist directory will generate a CSS folder, compressed CSS file is placed in this folder.

gulp-cssnano plug-in is similar to the above steps. I will not demonstrate one by one here. You can install the gulp-cssnano plug-in yourself, and replace the gulp-clean-css with the gulp-cssnano plug-in. Run the command, and the CSS file can also be successfully compressed.


知否
221 声望177 粉丝

Skrike while the iron is hot.