1. 程式人生 > 其它 >hexo 部落格支援PWA和壓縮博文

hexo 部落格支援PWA和壓縮博文

目標網站

https://blog.rmiao.top/

PWA

yarn add hexo-offline

然後在root config.yml裡新增

# offline config passed to sw-precache.
service_worker:
  maximumFileSizeToCacheInBytes: 5242880
  staticFileGlobs:
  - /**/*.{js,html,css,png,jpg,gif,svg,eot,ttf,woff,woff2}
  - /lib/**/*.js
  - /lib/**/*.css
  - /images/*
  - /js/src/**/*.js
  stripPrefix: public
  verbose: true
  runtimeCaching:
    - urlPattern: /*
      handler: cacheFirst
      options:
        origin: cdn.bootcss.com

然後新增manifest.json, 比如我使用了 hexo-theme-next的主題,在layout/_custom/header.swig 中引用了manifest.json

<link rel="manifest" href="/manifest.json">

manifest生成地址: https://app-manifest.firebaseapp.com/

比如,我的為

{
    "name": "風 - Ryan Miao",
    "short_name": "風",
    "theme_color": "#2196f3",
    "background_color": "#2196f3",
    "display": "browser",
    "scope": "/",
    "start_url": "/"
  }

具體快取策略還是看下官方文件,這裡不求甚解快取。重啟部落格,開啟控制檯,檢視網路,會發現,所有的檔案都是(from ServiceWorker) 或者(from disk cache)或者(from memory cache)

當hexo g之後,會多出一個service-worker.js裡面則是會快取的內容。

壓縮

看了下計算,壓縮大概可以節省一半空間。

$ npm install gulp -g
$ npm install gulp-minify-css gulp-uglify gulp-htmlmin gulp-htmlclean gulp --save

或者使用yarn 

yarn global add gulp
yarn add gulp-minify-css gulp-uglify gulp-htmlmin gulp-htmlclean gulp

然後,在根目錄新增 gulpfile.js :

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');
// 壓縮 public 目錄 css
gulp.task('minify-css', function() {
    return gulp.src('./public/**/*.css')
        .pipe(minifycss())
        .pipe(gulp.dest('./public'));
});
// 壓縮 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'))
});
// 壓縮 public/js 目錄 js
gulp.task('minify-js', function() {
    return gulp.src('./public/**/*.js')
        .pipe(uglify())
        .pipe(gulp.dest('./public'));
});
// 執行 gulp 命令時執行的任務
gulp.task('default', [
    'minify-html','minify-css','minify-js'
]);

執行:

hexo clean && hexo g && gulp &&  hexo s

參考

https://blog.naaln.com/2017/09/hexo-with-pwa/