Zong
前端优化之静态资源优化

废话不多说,使用gulp自动化构建工具来压缩代码文件。

1.安装gulp

$ npm install gulp -g
$ npm install gulp gulp-htmlclean gulp-htmlmin gulp-minify-css gulp-uglify --save

或者配置package.json后执行$ npm install

"dependencies": {
    "gulp": "^3.9.1",
    "gulp-htmlclean": "^2.7.14",
    "gulp-htmlmin": "^3.0.0",
    "gulp-minify-css": "^1.2.4",
    "gulp-uglify": "^2.1.2",
  }

2.创建gulpfile.js

/*
 * @此配置用于hexo
 */

var gulp = require('gulp');
var minifycss = require('gulp-minify-css');
var uglify = require('gulp-uglify');
var htmlmin = require('gulp-htmlmin');
var htmlclean = require('gulp-htmlclean');

// 压缩 public 目录 css
gulp.task('minify-css', function() {
    return gulp.src('./public/**/*.css')
        .pipe(minifycss())
        .pipe(gulp.dest('./public'));
});

// 压缩 public 目录 html
gulp.task('minify-html', function() {
    return gulp.src('./public/**/*.html')
        .pipe(htmlclean())
        .pipe(htmlmin({
            removeComments: true,  //清除HTML注释
            collapseWhitespace: true,  //压缩HTML
            collapseBooleanAttributes: true,  //省略布尔属性的值 <input checked="true"/> ==> <input checked />
            removeEmptyAttributes: true,  //删除所有空格作属性值 <input id="" /> ==> <input />
            removeScriptTypeAttributes: true,  //删除<script>的type="text/javascript"
            removeStyleLinkTypeAttributes: true,  //删除<style>和<link>的type="text/css"
            minifyJS: true,  //压缩页面JS
            minifyCSS: true  //压缩页面CSS
        }))
        .on('error', function(err) {
            console.log('html Error!', err.message);
            this.end();
        })
        .pipe(gulp.dest('./public'))
});

// 压缩 public/js 目录 js
gulp.task('minify-js', function() {
    return gulp.src('./public/**/*.js')
        .pipe(uglify())
        .pipe(gulp.dest('./public'));
});

// 执行 gulp 命令时执行的任务
gulp.task('default', [
    'minify-html','minify-css','minify-js',
]);

3.压缩静态资源

以后generate的时候跟上gulp命令即可压缩静态资源。

$ hexo g
$ gulp
$ hexo d