本文最后更新于 almost 2 years ago,文中所描述的信息可能已发生改变。
TIP提示
参考了安知鱼的方案进行修改 原教程butterfly 重装日记
TIP提示
参考了店长的方案进行修改 原教程Butterfly主题的PWA实现方案
安装
安装Gulp插件
在博客根目录[Blogroot]
打开终端,输入
shell
npm install --global gulp-cli #全局安装gulp指令集
npm install workbox-build gulp --save #安装gulp插件
压缩html插件
shell
npm install gulp-htmlclean --save-dev
npm install --save gulp-htmlmin
压缩css插件
shell
npm install gulp-clean-css --save-dev
压缩js插件
shell
npm install gulp-terser --save-dev
npm install --save-dev gulp-babel @babel/core @babel/preset-env
压缩图片插件
shell
npm install --save-dev gulp-imagemin
压缩字体插件
shell
npm install gulp-fontmin --save-dev
配置
添加
在package.json
中添加
JSON
+ "type": "module",
"dependencies":
创建
gulpfile.js
在Hexo
的根目录,创建一个gulpfile.js
文件,打开[Blogroot]/gulpfile.js
js
import gulp from 'gulp';
import cleanCSS from 'gulp-clean-css';
import htmlmin from 'gulp-htmlmin';
import htmlclean from 'gulp-htmlclean';
import workbox from 'workbox-build';
import fontmin from 'gulp-fontmin';
import terser from 'gulp-terser';
//pwa
gulp.task('generate-service-worker', () => {
return workbox.injectManifest({
swSrc: './sw-template.js',
swDest: './public/sw.js',
globDirectory: './public',
globPatterns: [
// 缓存所有以下类型的文件,极端不推荐
// "**/*.{html,css,js,json,woff2,xml}"
// 推荐只缓存404,主页和主要样式和脚本。
'404.html',
'index.html',
'js/main.js',
'css/index.css',
],
modifyURLPrefix: {
'': './',
},
});
});
gulp.task('compress', async() =>{
gulp
.src([
'./public/**/*.js',
'!./public/**/*.min.js',
'!./public/js/custom/galmenu.js',
'!./public/js/custom/gitcalendar.js',
])
.pipe(terser())
.pipe(gulp.dest('./public'))
});
//css
gulp.task('minify-css', () => {
return gulp
.src('./public/**/*.css')
.pipe(
cleanCSS({
compatibility: 'ie11',
})
)
.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'));
});
//压缩字体
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']) //HTML文件所在目录请根据自身情况修改
.on('data', function (file) {
buffers.push(file.contents);
})
.on('end', function () {
var text = Buffer.concat(buffers).toString('utf-8');
minifyFont(text, cb);
});
});
// 执行 gulp 命令时执行的任务
gulp.task(
'default',
gulp.series(
'generate-service-worker',
gulp.parallel('compress', 'minify-html', 'minify-css', 'mini-font')
)
);
sw-template.js
在Hexo
的根目录,创建一个sw-template.js
文件,打开[Blogroot]/sw-template.js
js
const workboxVersion = '5.1.3';
importScripts(`https://storage.googleapis.com/workbox-cdn/releases/${workboxVersion}/workbox-sw.js`);
workbox.core.setCacheNameDetails({
prefix: '梦念逍遥',
});
workbox.core.skipWaiting();
workbox.core.clientsClaim();
// 注册成功后要立即缓存的资源列表
// 具体缓存列表在gulpfile.js中配置,见下文
workbox.precaching.precacheAndRoute(self.__WB_MANIFEST, {
directoryIndex: null,
});
// 清空过期缓存
workbox.precaching.cleanupOutdatedCaches();
// 图片资源(可选,不需要就注释掉)
workbox.routing.registerRoute(
/\.(?:png|jpg|jpeg|gif|bmp|webp|svg|ico)$/,
new workbox.strategies.CacheFirst({
cacheName: 'images',
plugins: [
new workbox.expiration.ExpirationPlugin({
maxEntries: 1000,
maxAgeSeconds: 60 * 60 * 24 * 30,
}),
new workbox.cacheableResponse.CacheableResponsePlugin({
statuses: [0, 200],
}),
],
})
)
// 字体文件(可选,不需要就注释掉)
workbox.routing.registerRoute(
/\.(?:eot|ttf|woff|woff2)$/,
new workbox.strategies.CacheFirst({
cacheName: 'fonts',
plugins: [
new workbox.expiration.ExpirationPlugin({
maxEntries: 1000,
maxAgeSeconds: 60 * 60 * 24 * 30,
}),
new workbox.cacheableResponse.CacheableResponsePlugin({
statuses: [0, 200],
}),
],
})
);
// 谷歌字体(可选,不需要就注释掉)
workbox.routing.registerRoute(
/^https:\/\/fonts\.googleapis\.com/,
new workbox.strategies.StaleWhileRevalidate({
cacheName: 'google-fonts-stylesheets',
})
);
workbox.routing.registerRoute(
/^https:\/\/fonts\.gstatic\.com/,
new workbox.strategies.CacheFirst({
cacheName: 'google-fonts-webfonts',
plugins: [
new workbox.expiration.ExpirationPlugin({
maxEntries: 1000,
maxAgeSeconds: 60 * 60 * 24 * 30,
}),
new workbox.cacheableResponse.CacheableResponsePlugin({
statuses: [0, 200],
}),
],
})
);
// jsdelivr的CDN资源(可选,不需要就注释掉)
workbox.routing.registerRoute(
/^https:\/\/cdn\.jsdelivr\.net/,
new workbox.strategies.CacheFirst({
cacheName: 'static-libs',
plugins: [
new workbox.expiration.ExpirationPlugin({
maxEntries: 1000,
maxAgeSeconds: 60 * 60 * 24 * 30,
}),
new workbox.cacheableResponse.CacheableResponsePlugin({
statuses: [0, 200],
}),
],
})
)
workbox.googleAnalytics.initialize();
图标
将你的图标包移入相应的目录,例如我是/img/siteicon/
,所以放到[Blogroot]/source/img/siteicon/
目录下。
新建文件名为manifest.json
并将其放到[Blogroot]/source
目录下,此时还不能直接用,需要添加一些内容,以下是我的manifest.json
配置内容,权且作为参考,其中的theme_color
建议用取色器取设计的图标的主色调,同时务必配置start_url
和name
的配置项,这关系到你之后能否看到浏览器的应用安装按钮(同时,格式一定要是png)
JSON
{
"name": "梦念逍遥`BLOG",
"short_name": "梦念逍遥",
"theme_color": "#425aef",
"background_color": "#425aef",
"display": "standalone",
"scope": "/",
"start_url": "/",
"icons": [{
"src": "/img/siteicon/16.png",
"sizes": "16x16",
"type": "image/png"
},
{
"src": "/img/siteicon/32.png",
"sizes": "32x32",
"type": "image/png"
},
{
"src": "/img/siteicon/48.png",
"sizes": "48x48",
"type": "image/png"
},
{
"src": "/img/siteicon/64.png",
"sizes": "64x64",
"type": "image/png"
},
{
"src": "/img/siteicon/128.png",
"sizes": "128x128",
"type": "image/png"
},
{
"src": "/img/siteicon/144.png",
"sizes": "144x144",
"type": "image/png"
},
{
"src": "/img/siteicon/512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"splash_pages": null
}
开启PWA
打开主题配置文件[Blogroot]/_config.butterfly.yml
,找到PWA配置项。添加图标路径。这里的theme_color
建议改成你图标的主色调,包括manifest.json
中的theme_color
也是如此.
yaml
pwa:
enable: true
manifest: /manifest.json
theme_color: "#3b70fc"
apple_touch_icon: /img/siteicon/128.png
favicon_32_32: /img/siteicon/32.png
favicon_16_16: /img/siteicon/16.png
mask_icon: /img/siteicon/128.png
运行命令
shell
hexo cl&&hexo g&&gulp
## 之后运行
hexo s 或者 hexo de