Hexo 压缩 HTML 源码

安装

npm install gulp             --global
npm install gulp-htmlclean   --save
npm install gulp-htmlmin     --save
npm install gulp-imagemin    --save
npm install gulp-minify-css  --save
npm install gulp-uglify      --save

根目录新建 gulpfile.js

var gulp = require('gulp'),
    rename = require('gulp-rename'),
    htmlclean = require('gulp-htmlclean');
    htmlmin = require('gulp-htmlmin');
    cssmin = require('gulp-clean-css'),
    uglify = require('gulp-uglify'),
    imagemin = require('gulp-imagemin');
    concat = require('gulp-concat');

// 压缩 HTML
gulp.task('htmlmin', function() {
  return gulp.src('./public/**/*.html')
    .pipe(htmlclean())
    .pipe(htmlmin({
         removeComments: true,
         minifyJS: true,
         minifyCSS: true,
         minifyURLs: true,
    }))
    .pipe(gulp.dest('./public'))
});

// 压缩 CSS
gulp.task('cssmin', function() {
    return gulp.src('./public/**/*.css')
        .pipe(cssmin())
        .pipe(gulp.dest('./public'));
});

// 合并 CSS
gulp.task('cssall', function () {
    return gulp.src('./public/**/*.css')
    // 压缩后重命名
        .pipe(concat('app.css'))
        .pipe(gulp.dest('./public'));
});

// 压缩 JS
gulp.task('jsmin', function() {
    return gulp.src('./public/**/*.js')
        .pipe(uglify())
        .pipe(gulp.dest('./public'));
});

// 合并 JS
gulp.task('jsall', function () {
    return gulp.src('./public/**/*.js')
    // 压缩后重命名
        .pipe(concat('app.js'))
        .pipe(gulp.dest('./public'));
});

// 压缩图片
gulp.task('images', function () {
    return gulp.src('./photos/*.*')
        .pipe(imagemin({
            progressive: true
        }))
        .pipe(gulp.dest('public/images'))
});
gulp.task('default', ['htmlmin', 'cssmin', 'cssall', 'jsmin', 'jsall','images']);

执行命令gulp后所有任务自动完成,命令只适用 hexo g 之后执行,代码自用。

博客暂时未启用:CSS,JS合并减少响应、图片压缩。

更多信息点:gulp.js – 基于流的自动化构建工具