默认情况下hexo g构建生成的代码是没有压缩的,在文件比较大时,影响加载速度,所以这里使用gulp帮助我们在构建后,做下代码压缩工作
安装gulp
在项目根目录下,命令行中输入以下指令,安装gulp
安装插件
在项目根目录下,命令行中如下以下指令,安装相关插件
1 2 3 4 5
| yarn add gulp-clean-css -D yarn add gulp-terser -D yarn add gulp-uglify -D yarn add gulp-html-minifier-terser -S yarn add gulp-htmlclean -S
|
编写gulp配置
在项目根目录新建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
| const gulp = require('gulp') const cleanCSS = require('gulp-clean-css') const htmlmin = require('gulp-html-minifier-terser') const htmlclean = require('gulp-htmlclean') const terser = require('gulp-terser');
// 压缩 js gulp.task('compress', () => gulp.src(['./public/**/*.js', '!./public/**/*.min.js']) .pipe(terser()) .pipe(gulp.dest('./public')) )
// 压缩 css gulp.task('minify-css', () => { return gulp.src('./public/**/*.css') .pipe(cleanCSS()) .pipe(gulp.dest('./public')) })
// 壓縮 public 目錄內 html gulp.task('minify-html', () => { return gulp.src('./public/**/*.html') .pipe(htmlclean()) .pipe(htmlmin({ removeComments: true, // 清除 HTML 註釋 collapseWhitespace: true, // 壓縮 HTML collapseBooleanAttributes: true, // 省略布爾屬性的值 <input checked="true"/> ==> <input /> removeEmptyAttributes: true, // 刪除所有空格作屬性值 <input id="" /> ==> <input /> removeScriptTypeAttributes: true, // 刪除 <script> 的 type="text/javascript" removeStyleLinkTypeAttributes: true, // 刪除 <style> 和 <link> 的 type="text/css" minifyJS: true, // 壓縮頁面 JS minifyCSS: true, // 壓縮頁面 CSS minifyURLs: true })) .pipe(gulp.dest('./public')) })
// 執行 gulp 命令時執行的任務 gulp.task('default', gulp.parallel( 'compress', 'minify-css', 'minify-html' ))
|
修改package.json
修改package.json的script如下,在build构建成功后,执行gulp命令,对资源进行处理
1 2 3 4 5 6 7 8
| "scripts": { "dev": "hexo server", "build": "hexo clean && hexo g && hexo algolia && gulp", "clean": "hexo clean", "deploy": "hexo clean && hexo g && gulp && hexo deploy", "search": "hexo clean && hexo g && hexo algolia", "gulp": "hexo g && gulp" }
|