通过Gulp压缩Hexo打包生成的静态资源

安装配置gulp

1、安装gulp

1
npm install --global gulp-cli

2、安装相关压缩模块

1
2
3
4
npm install gulp --save
npm install gulp-htmlclean gulp-htmlmin gulp-clean-css gulp-uglify gulp-imagemin --save
npm install gulp-babel babel-preset-env babel-preset-mobx --save
npm install -D @babel/core @babel/preset-react @babel/preset-env --save

3、在hexo目录创建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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79

let gulp = require('gulp')
let cleanCSS = require('gulp-clean-css')
let htmlmin = require('gulp-htmlmin')
let htmlclean = require('gulp-htmlclean')
let babel = require('gulp-babel') /* 转换为es2015 */
let uglify = require('gulp-uglify')
let imagemin = require('gulp-imagemin')

// 设置根目录
const root = './public'

// 匹配模式, **/*代表匹配所有目录下的所有文件
const pattern = '**/*'

// 压缩html
gulp.task('minify-html', function() {
return gulp
// 匹配所有 .html结尾的文件
.src(`${root}/${pattern}.html`)
.pipe(htmlclean())
.pipe(
htmlmin({
removeComments: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true
})
)
.pipe(gulp.dest('./public'))
})

// 压缩css
gulp.task('minify-css', function() {
return gulp
// 匹配所有 .css结尾的文件
.src(`${root}/${pattern}.css`)
.pipe(
cleanCSS({
compatibility: 'ie8'
})
)
.pipe(gulp.dest('./public'))
})

// 压缩js
gulp.task('minify-js', function() {
return gulp
// 匹配所有 .js结尾的文件
.src(`${root}/${pattern}.js`)
.pipe(
babel({
presets: ['env']
})
)
.pipe(uglify())
.pipe(gulp.dest('./public'))
})

// 压缩图片
gulp.task('minify-images', function() {
return gulp
// 匹配public/images目录下的所有文件
.src(`${root}/images/${pattern}`)
.pipe(
imagemin(
[
imagemin.gifsicle({ optimizationLevel: 3 }),
imagemin.jpegtran({ progressive: true }),
imagemin.optipng({ optimizationLevel: 7 }),
imagemin.svgo()
],
{ verbose: true }
)
)
.pipe(gulp.dest('./public/images'))
})

gulp.task('default', gulp.series('minify-html', 'minify-css', 'minify-js'))

其中,gulp 3.x和4.x版本语法有些许不同,gulp 3.x版本的gulp.series()函数可以接受一个或多个函数,而gulp 4.x版本的gulp.series()函数只能接受一个函数。

1
2
3
4
5
//v3版本执行语法
gulp.task('default', gulp.parallel('compress', 'minify-css', 'minify-html', 'minify-images'))

//gulp 4.0.2新语法修改
gulp.task('default', gulp.series('compress', 'minify-css', 'minify-html'))

4、压缩

1
gulp

生成流程

1
2
3
4
hexo clean
hexo g
gulp
hexo d

参考文章