Hexo使用gulp压缩代码

在hexo的根目录下执行以下命令:

1
2
npm install gulp -g
npm install gulp-minify-css gulp-uglify gulp-htmlmin gulp-htmlclean gulp --save

接着,在hexo的根目录下新建文件gulpfile.js

1
vim 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
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,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
}))
.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'
]);

此时,在执行完hexo g之后,执行gulp命令即可对静态资源(JS\CSS)进行打包

1
2
3
4
5
6
7
8
9
10
gulp
[21:47:32] Using gulpfile ~/blog/gulpfile.js
[21:47:32] Starting 'minify-html'...
[21:47:32] Starting 'minify-css'...
[21:47:32] Starting 'minify-js'...
[21:47:36] Finished 'minify-css' after 3.79 s
[21:47:44] Finished 'minify-js' after 12 s
[21:47:46] Finished 'minify-html' after 14 s
[21:47:46] Starting 'default'...
[21:47:46] Finished 'default' after 33 μs

以后发布文章的时候使用如下命令:

1
2
3
4
hexo clean
hexo g
gulp
hexo d
Cco.Xyz wechat
坚持原创技术分享,您的支持将鼓励我继续创作!
0%