hexo-all-minifier 资源压缩

项目地址

https://github.com/chenzhutian/hexo-all-minifier

使用方法

安装

$ npm install hexo-all-minifier --save

简单配置

在 _config.yml 里添加

all_minifier: true

全部配置

详细说明见 README

html_minifier:
  enable: true
  ignore_error: false
  exclude:

css_minifier:
  enable: true
  exclude:
    - '*.min.css'

js_minifier:
  enable: true
  mangle: true
  compress:
  exclude:
    - '*.min.js'

js_concator:
  enable: false
  bundle_path: '/js/bundle.js'
  front: false
  silent: false

image_minifier:
  enable: true
  interlaced: false
  multipass: false
  optimizationLevel: 2
  pngquant: false
  progressive: false

源码学习

// /node_modules/hexo-all-minifier/index.js

const isEnabled = process.env.NODE_ENV !== 'development'
  && (hexo.config.hasOwnProperty('all_minifier') === false || 
  hexo.config.all_minifier === true);

if (isEnabled) {
  // ...
}

由于压缩处理时间较长,开发时热更频繁,所以这里判断了环境变量,开发环境不启用压缩,也是挺人性化的,所以我们的 npm 脚本可以写成这样 "dev": "NODE_ENV=development hexo s"

// /node_modules/hexo-all-minifier/index.js

if (isEnabled) {
  // HTML minifier
  hexo.config.html_minifier = Object.assign({
    enable: true,
    exclude: [],
    ignoreCustomComments: [/^\s*more/],
    removeComments: true,
    removeCommentsFromCDATA: true,
    collapseWhitespace: true,
    collapseBooleanAttributes: true,
    removeEmptyAttributes: true,
    minifyJS: true,
    minifyCSS: true,
    silent: false
  }, hexo.config.html_minifier);

  // Css minifier
  hexo.config.css_minifier = Object.assign({
    enable: true,
    exclude: ['*.min.css'],
    silent: false
  }, hexo.config.css_minifier);

  // Js minifier
  hexo.config.js_minifier = Object.assign({
    enable: true,
    mangle: true,
    output: {},
    compress: {},
    exclude: ['*.min.js'],
    silent: false
  }, hexo.config.js_minifier);

  // Image minifier
  hexo.config.image_minifier = Object.assign({
    enable: true,
    interlaced: false,
    multipass: false,
    optimizationLevel: 3,
    pngquant: false,
    progressive: false,
    silent: false
  }, hexo.config.image_minifier);

  // Js concator
  hexo.config.js_concator = Object.assign({
    enable: false,
    bundle_path: 'js/bundle.js',
    front: false,
    silent: false
  }, hexo.config.js_concator);

  hexo.extend.filter.register('after_render:html', require('./lib/optimizeHTML'));
  hexo.extend.filter.register('after_render:css', require('./lib/optimizeCSS'));
  hexo.extend.filter.register('after_render:js', require('./lib/optimizeJS'));
  hexo.extend.filter.register('after_generate', require('./lib/optimizeImage'));
  hexo.extend.filter.register('after_generate', require('./lib/concatJS'));
}

这里初始化了一些默认的配置项,然后注册了一些渲染后钩子函数,处理函数在 ./lib 文件夹下。

  • optimizeHTML 依赖 html-minifier
  • optimizeCSS 依赖 clean-css
  • optimizeJS 依赖 uglify-es
  • optimizeImage 依赖 imagemin

问题解决

  1. 图片压缩报错
# Hint
$ Error: spawn /.../node_modules/jpegtran-bin/vendor/jpegtran ENOENT

# 解决方案
# Reference: https://github.com/imagemin/imagemin/issues/154
$ yarn add -D jpegtran-bin