前言
gulp能够帮助用户自动压缩静态资源,配合各类下属插件,能够压缩包括css、js、html乃至各类格式的图片文件。
配置教程
- 安装gulp插件
1 2
| npm install --global gulp-cli npm install gulp --save
|
- 安装各个下属插件以实现对各类静态资源的压缩。
1 2 3 4 5 6 7 8 9 10 11 12
| 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
|
- 为Gulp创建
gulpfile.js
任务脚本。在博客根目录[Blogroot]
下新建gulpfile.js
,打开[Blogroot]\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
| 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 uglify = require('gulp-uglify') var babel = require('gulp-babel')
gulp.task('compress', async() => gulp.src(['./public/**/*.js', '!./public/**/*.min.js']) .pipe(babel({ presets: ['@babel/preset-env'] })) .pipe(uglify().on('error', function (e) { console.log(e) })) .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' ))
|
- 在每次运行完
hexo generate
生成静态页面后,运行gulp
对其进行压缩。指令流程如下:
1 2 3 4
| hexo clean hexo generate gulp hexo deploy
|
可以发现资源加载速度快了很多。