虽然本站大部分静态文件都使用了CDN,但是一些html文件依然存在大量的空白字符。通过Github Actions既不用增加部署命令,又可以实现静态文件的压缩,何乐而不为呢?
本地安装Gulp 首先全局安装gulp
接着分别安装相关的html、js、css、image插件,后面这些主要是为了解决兼容的问题
1 2 3 4 5 6 7 8 9 10 11 12 13 npm install gulp --save npm install gulp-minify-css --save npm install gulp-uglify --save npm install gulp-htmlmin --save npm install gulp-htmlclean --save npm install gulp-imagemin --save # 解决【Gulp 打包问题】 GulpUglifyError : unable to minify JavaScript # 解决 gulp-uglify 压缩JavaScript 不兼容 es5 语法的问题 npm install babel-core@6.26 .3 --save npm install gulp-babel@7.0 .1 --save npm install babel-preset-es2015@6.24 .1 --save # gulp-babel 取消严格模式方法("use strict" ) npm install babel-plugin-transform-remove-strict-mode --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 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 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' );var imagemin = require ('gulp-imagemin' );var babel = require ('gulp-babel' );gulp.task ('minify-css' , function (done ) { return gulp.src ('./public/**/*.css' ) .pipe (minifycss ()) .pipe (gulp.dest ('./public' )); done (); }); gulp.task ('minify-html' , function (done ) { return gulp.src ('./public/**/*.html' ) .pipe (htmlclean ()) .pipe (htmlmin ({ removeComments : true , minifyJS : true , minifyCSS : true , minifyURLs : true , })) .pipe (gulp.dest ('./public' )); done (); }); gulp.task ('minify-js' , function (done ) { return gulp.src (['./public/**/*.js' , '!./public/**/*.min.js' ]) .pipe (babel ({ presets : ['es2015' ] })) .pipe (uglify ()) .pipe (gulp.dest ('./public' )); done (); }); gulp.task ('minify-images' , 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.series (gulp.parallel ('minify-html' , 'minify-css' , 'minify-js' , 'minify-images' )), function ( ) { console .log ("----------gulp Finished----------" ); });
创建.babelrc
文件 依然是在根目录新建即可
1 2 3 4 { 'presets' : ['es2015' ], "plugins" : ["transform-remove-strict-mode" ] }
修改Acitons配置文件 修改.github/workflows/main.yml
文件,这里我参考的Travis CI的配置,因为网上还没有Github Actions安装gulp相关的内容。
1 2 3 npm install hexo-cli -g npm install gulp -g npm install
1 2 3 4 hexo clean hexo g gulp hexo d
自动触发 接着使用git push即可自动触发gulp压缩静态文件并部署到Github Pages
压缩效果 html压缩前24KB,压缩后17KB,减少29%的体积
css和js也有接近30%的压缩,图片则没有效果,因为除了logo和ico全是用的CDN