hexoHexo教程Hexo博客使用gulp插件压缩网站资源
oO天云空影Oogulp
能够帮助用户自动压缩静态资源,配合各类下属插件,能够压缩包括css、js、html乃至各类格式的图片文件。(图片文件的压缩往往只能节省几十KB,效果远远不如imagine、tinypng等压缩方式,所以此处不再写使用gulp压缩图片的内容)。
安装插件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| npm install --global gulp-cli npm install gulp --save
npm install gulp-htmlclean --save-dev npm install gulp-html-minifier-terser --save-dev
npm install gulp-clean-css --save-dev
npm install gulp-terser --save-dev
npm install gulp-fontmin --save-dev
|
新建gulpfile.js
文件
gulp-terser只会直接压缩js代码,所以不存在因为语法变动导致的错误 。事实上,当我们使用jsdelivr的CDN服务时,只需要在css或者js的后缀前添加.min,例如example.js->example.min.js,JsDelivr就会自动使用terser帮我们压缩好代码
在博客根目录下新建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
| var gulp = require('gulp'); var cleanCSS = require('gulp-clean-css'); var htmlmin = require('gulp-html-minifier-terser'); var htmlclean = require('gulp-htmlclean'); var fontmin = require('gulp-fontmin');
var terser = require('gulp-terser');
gulp.task('compress', async() =>{ gulp.src(['./public/**/*.js', '!./public/**/*.min.js']) .pipe(terser()) .pipe(gulp.dest('./public')) });
gulp.task('minify-css', () => { return gulp.src(['./public/**/*.css']) .pipe(cleanCSS({ compatibility: 'ie11' })) .pipe(gulp.dest('./public')); });
gulp.task('minify-html', () => { return gulp.src('./public/**/*.html') .pipe(htmlclean()) .pipe(htmlmin({ removeComments: true, collapseWhitespace: true, collapseBooleanAttributes: true, removeEmptyAttributes: true, removeScriptTypeAttributes: true, removeStyleLinkTypeAttributes: true, minifyJS: true, minifyCSS: true, minifyURLs: true })) .pipe(gulp.dest('./public')) });
function minifyFont(text, cb) { gulp .src('./public/fonts/*.ttf') .pipe(fontmin({ text: text })) .pipe(gulp.dest('./public/fontsdest/')) .on('end', cb); }
gulp.task('mini-font', (cb) => { var buffers = []; gulp .src(['./public/**/*.html']) .on('data', function(file) { buffers.push(file.contents); }) .on('end', function() { var text = Buffer.concat(buffers).toString('utf-8'); minifyFont(text, cb); }); });
gulp.task('default', gulp.parallel( 'compress', 'minify-css', 'minify-html','mini-font' ))
|
编译预览
1
| hexo cl | hexo g | gulp | hexo s
|
本文参考:
使用gulp压缩博客静态资源