ILLUSTRATION

hexo博客压缩css、js等文件

参考:

https://www.voidking.com/dev-hexo-gulp/

https://qiita.com/SwuBHj8aKGqBKHet/items/bc206375942c0f6a93fe

安装gulp

1
2
3
4
5
6
sudo npm install --global gulp-cli
# 博客目录下
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

配置 gulpfile.js

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
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: ['@babel/preset-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命令即可执行压缩

比如我的public文件夹从25M压缩到了13M

将命令设置到package.json

1
2
3
"scripts": {
"build": "hexo clean && hexo generate && gulp",
}

然后执行

1
2
npm run build
hexo server # 或者 hexo deploy