Using gulp to compress blog static resources

Posted by Joe689 on Thu, 20 Jan 2022 07:07:47 +0100

Update record

2022-01-19: text migration

  1. Migrate gulp content from collections to stand-alone articles
  2. New font compression related content

Reference direction

Tutorial original post

Gulp official documents are used to find API usage and view the included gulp plug-ins

gulp.js Chinese document

Refer to the basic scheme of Gulp compression

Butterfly theme document Gulp compression

The optimization scheme of gulp is referred

Excellent technology - how to optimize blog

Refer to the font compression scheme found by Xiao Wei

Xiaowei fontmin&&hexo font compression

Gulp fontmin documentation

gulp-fontmin

Write first

gulp It can help users automatically compress static resources, cooperate with various subordinate plug-ins, and compress picture files including css, js, html and even various formats. (image file compression can only save tens of KB, which is far less effective than image, tinypng and other compression methods, so gulp is no longer used to compress images here).

Configuration tutorial

Install Gulp plug-in: open the terminal in the blog root directory [Blogroot], and enter:

npm install --global gulp-cli #Global install gulp instruction set
npm install gulp --save #Installing the gulp plug-in

Install various subordinate plug-ins to compress various static resources. Here we shout excellence technology NB!

Compress HTML:

npm install gulp-htmlclean --save-dev
npm install gulp-html-minifier-terser --save-dev
# You can compress the ES6 syntax in HTML with gulp HTML minifier terser

Compress CSS:

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

Compressed JS

Butterfly theme document Two plug-in schemes for compressing js are provided. The difference between the two is that terser is a JavaScript parser for ES6 +, while gulp Babel is a JavaScript conversion compiler, which can convert ES6 to ES5. Both schemes are effective. But each has its own advantages and disadvantages. Considering the current browser market share, it is more recommended that you use terser to compress js.

Scheme 1: in order to adapt to most browsers (IE: Lao Tzu), ES6 syntax can be reduced to ES5 syntax. Then use gulp-babel , after using ES6 js in the compression part of this scheme, a series of mysterious bug s will be caused due to the change of variable life cycle caused by forced degradation. You need to manually add shielding items to select the corresponding js not to be compressed.

npm install gulp-uglify --save-dev
npm install gulp-babel @babel/core @babel/preset-env --save-dev

Scheme II (more recommended): gulp-terser It only compresses JS code directly, so there are no errors caused by syntax changes. In fact, when we use the CDN service of jsdelivr, we only need to add it before the suffix of css or JS min, for example js->example. min.js, jsdelivr will automatically use terser to help us compress the code.

npm install gulp-terser --save-dev

Compressed font package

Font files are the most loved and hated static resources. In order to ensure the text matching of the site, the font package of the whole font library often exceeds 15MB, which puts great pressure on the loading speed of the blog. fontmin can traverse the characters used in the blog, extract the font styles of these characters in the font package, and output them as a new font package.

Font min only supports compressed ttf font packages

npm install gulp-fontmin --save-dev

Create a gulpfile for Gulp JS task script. Create a new gulpfile under the blog root directory [Blogroot] JS, open [Blogroot] \ gulpfile JS, enter the following:

  • Scheme 1: babel compression js
//Various plug-ins used
var gulp = require('gulp');
var cleanCSS = require('gulp-clean-css');
var htmlmin = require('gulp-html-minifier-terser');
var htmlclean = require('gulp-htmlclean');
var fontmin = require('gulp-fontmin');
var uglify = require('gulp-uglify')
var babel = require('gulp-babel')
//Compress js
gulp.task('compress', () =>
  gulp.src(['./public/**/*.js', '!./public/**/*.min.js'])
    .pipe(babel({
      presets: ['@babel/preset-env']
    }))
    .pipe(uglify().on('error', function (e) {
      console.log(e)
    }))
    .pipe(gulp.dest('./public'))
)
//Compress css
gulp.task('minify-css', () => {
    return gulp.src(['./public/**/*.css'])
        .pipe(cleanCSS({
            compatibility: 'ie11'
        }))
        .pipe(gulp.dest('./public'));
});
//Compress html
gulp.task('minify-html', () => {
    return gulp.src('./public/**/*.html')
        .pipe(htmlclean())
        .pipe(htmlmin({
            removeComments: true, //Clear html comments
            collapseWhitespace: true, //Compress html
            collapseBooleanAttributes: true,
            //Omit the value of Boolean attribute, for example: < input checked = "true" / > = > < input / >
            removeEmptyAttributes: true,
            //Delete all spaces as attribute values, for example: < input id = "" / > = > < input / >
            removeScriptTypeAttributes: true,
            //Delete type="text/javascript" of < script >
            removeStyleLinkTypeAttributes: true,
            //Delete type="text/css" for < style > and < link >
            minifyJS: true, //Compressed page JS
            minifyCSS: true, //Compress page CSS
            minifyURLs: true  //Compress page URL
        }))
        .pipe(gulp.dest('./public'))
});
//Compressed font
function minifyFont(text, cb) {
  gulp
    .src('./public/fonts/*.ttf') //Directory of original font
    .pipe(fontmin({
      text: text
    }))
    .pipe(gulp.dest('./public/fontsdest/')) //Compressed output directory
    .on('end', cb);
}

gulp.task('mini-font', (cb) => {
  var buffers = [];
  gulp
    .src(['./public/**/*.html']) //Please modify the directory where the HTML file is located according to your own situation
    .on('data', function(file) {
      buffers.push(file.contents);
    })
    .on('end', function() {
      var text = Buffer.concat(buffers).toString('utf-8');
      minifyFont(text, cb);
    });
});
// When running the gulp command, perform the following tasks in turn
gulp.task('default', gulp.parallel(
  'compress', 'minify-css', 'minify-html','mini-font'
))
  • Scheme 2: terser compression js (recommended)
//Various plug-ins used
var gulp = require('gulp');
var cleanCSS = require('gulp-clean-css');
var htmlmin = require('gulp-html-minifier-terser');
var htmlclean = require('gulp-htmlclean');
var fontmin = require('gulp-fontmin');
// gulp-tester
var terser = require('gulp-terser');
// Compress js
gulp.task('compress', () =>
  gulp.src(['./public/**/*.js', '!./public/**/*.min.js'])
    .pipe(terser())
    .pipe(gulp.dest('./public'))
)
//Compress css
gulp.task('minify-css', () => {
    return gulp.src(['./public/**/*.css'])
        .pipe(cleanCSS({
            compatibility: 'ie11'
        }))
        .pipe(gulp.dest('./public'));
});
//Compress html
gulp.task('minify-html', () => {
    return gulp.src('./public/**/*.html')
        .pipe(htmlclean())
        .pipe(htmlmin({
            removeComments: true, //Clear html comments
            collapseWhitespace: true, //Compress html
            collapseBooleanAttributes: true,
            //Omit the value of Boolean attribute, for example: < input checked = "true" / > = > < input / >
            removeEmptyAttributes: true,
            //Delete all spaces as attribute values, for example: < input id = "" / > = > < input / >
            removeScriptTypeAttributes: true,
            //Delete type="text/javascript" of < script >
            removeStyleLinkTypeAttributes: true,
            //Delete type="text/css" for < style > and < link >
            minifyJS: true, //Compressed page JS
            minifyCSS: true, //Compress page CSS
            minifyURLs: true  //Compressed page URL
        }))
        .pipe(gulp.dest('./public'))
});
//Compressed font
function minifyFont(text, cb) {
  gulp
    .src('./public/fonts/*.ttf') //Directory of original font
    .pipe(fontmin({
      text: text
    }))
    .pipe(gulp.dest('./public/fontsdest/')) //Compressed output directory
    .on('end', cb);
}

gulp.task('mini-font', (cb) => {
  var buffers = [];
  gulp
    .src(['./public/**/*.html']) //Please modify the directory where the HTML file is located according to your own situation
    .on('data', function(file) {
      buffers.push(file.contents);
    })
    .on('end', function() {
      var text = Buffer.concat(buffers).toString('utf-8');
      minifyFont(text, cb);
    });
});
// When running the gulp command, perform the following tasks in turn
gulp.task('default', gulp.parallel(
  'compress', 'minify-css', 'minify-html','mini-font'
))

Run gulp to compress the static page after each run of hexo generate. The instruction flow is as follows:

hexo clean
hexo generate
gulp
hexo server or hexo deploy

In this article, the supplementary description of font min is to read the characters in all compiled html files (. / public/**/*.html), and then match the characters in the original font package/ public/fonts/*.ttf font style, output the compressed font package to/ public/fontsdest / directory. Therefore, the relative path of the final reference font should be / fontsdest / * ttf. In the local test, if gulp is not run, the compressed font package will not be output to the public directory, and the font style will not be seen.