hexo作为静态页面来说加载速度已经很快了,但是我们仍然可以通过基于Node.js名为gulp的自动化构建工具实现对html、css、js等静态资源的压缩,进一步优化博客访问速度。

一、安装

先在cmd全局安装gulp

1
npm install gulp

再到项目路径安装所需要的模块

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

二、创建gulpfile.js文件

在根目录下,新建gulpfile.js文件,文件内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//Plugins模块获取
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');

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

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

.pipe(gulp.dest('./public'))
});

//压缩js 不压缩min.js
gulp.task('minify-js', async function () {
return gulp.src(['./public/**/*.js', '!./public/**/*.min.js'])
.pipe(uglify())
.pipe(gulp.dest('./public'));
});

// 压缩 public/images 目录内图片(Version>3)
gulp.task('minify-images', async function (done) {
gulp.src('./public/images/**/*.*')
.pipe(imagemin([
imagemin.gifsicle({interlaced: true}),
imagemin.jpegtran({progressive: true}),
imagemin.optipng({optimizationLevel: 5}),
imagemin.svgo({
plugins: [
{removeViewBox: true},
{cleanupIDs: false}
]
})
]))
.pipe(gulp.dest('./public/images'));
done();
});
// 开始任务
gulp.task('default', gulp.parallel('minify-html', 'minify-css', async function() {
// Do something after a, b, and c are finished.
}));

三、执行压缩

每次在执行 generate 命令后执行 gulp 就可以实现对静态资源的压缩

1
2
hexo g
gulp