基於Hexo搭建個人博客優化(五)---壓縮篇(gulp4.0壓縮靜態資源)

本章主要記錄瞭如何通過gulp工具壓縮壓縮博客靜態文件以加快網站加載速度。

這是一個基於Hexo的個人博客的教程,包含了從博客搭建到主題優化,最後部署到雲端的全過程。

更多文章歡迎訪問我的個人博客–>幻境雲圖

在本系列文章的第二章中也有類似靜態資源壓縮的教程,是用的hexo-neat插件,最近用着用着出現了一點點問題,無奈之下換用了gulp。這個工具也可以很方便的壓縮靜態資源。

1. 插件安裝

首先需要安裝gulp工具

命令:npm install gulp

接着安裝功能模塊,包括

gulp-htmlclean // 清理html
gulp-htmlmin // 壓縮html
gulp-minify-css // 壓縮css
gulp-uglify // 混淆js

命令:npm install gulp-htmlclean gulp-htmlmin gulp-minify-css gulp-uglify --save

2. 創建任務

在站點根目錄下,新建gulpfile.js文件,文件內容如下:

var gulp = require('gulp');

//Plugins模塊獲取
var minifycss = require('gulp-minify-css');
var uglify = require('gulp-uglify');
var htmlmin = require('gulp-htmlmin');
var htmlclean = require('gulp-htmlclean');
//壓縮css
gulp.task('minify-css', function () {
return gulp.src('./public/**/*.css')
.pipe(minifycss())
.pipe(gulp.dest('./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'))
});
//壓縮js 不壓縮min.js
gulp.task('minify-js', function () {
return gulp.src(['./public/**/*.js', '!./public/**/*.min.js'])
.pipe(uglify())
.pipe(gulp.dest('./public'));
});

//4.0以前的寫法 
//gulp.task('default', [
  //  'minify-html', 'minify-css', 'minify-js'
//]);
//4.0以後的寫法
// 執行 gulp 命令時執行的任務
gulp.task('default', gulp.parallel('minify-html', 'minify-css', 'minify-js', function() {
  // Do something after a, b, and c are finished.
}));
 

3. 使用

使用時按照以下順序就可以了:

hexo clean //先清理文件
hexo g  //編譯生成靜態文件
gulp  //gulp插件執行壓縮任務
hexo s //開啓服務

4. 問題

剛開始弄這個的時候也是各種百度,Google,大部分的文章也是這麼寫的但是,第二部的js 代碼卻都有問題,也不能說有問題吧,大部分都是4.0以前的寫法,導致現在gulp更新到4.0之後全都無法使用了。可能在看到這篇文章之前也試了各種辦法。然後每次都出現這樣的問題:

assert.js:85
  throw new assert.AssertionError({
  ^
AssertionError: Task function must be specified
    at Gulp.set [as _setTask] (/home/hope/web/node_modules/undertaker/lib/set-task.js:10:3)
    at Gulp.task (/home/hope/web/node_modules/undertaker/lib/task.js:13:8)
.................

在看了下gulp相關資料後才發現了問題,接着把js代碼稍微改了改終於能用了。不過運行的時候好像也有點問題,不過不影響使用,對這些工具還是不太瞭解。

[21:35:20] The following tasks did not complete: default, <anonymous>
[21:35:20] Did you forget to signal async completion?
//代碼裏也沒這個任務呀
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章