vuepress-blog的性能优化-CDN
提示
博客网站性能优化之旅
# 概况
- 使用vuepress构建的博客
- 使用了vuepress-theme-repo的主题
# 问题
网站打开的速度比较慢,使用chrome加载资源瀑布流分析, 图片、js资源加载速度太慢了, 不是很大,几十k,最大的js,170k,但是加载时间却要5s、10s的,受不了!!!急需优化。
# 优化
# 个人站点
之前购买腾讯云的服务器, 配置较低
# 优化策略
- 构建时自定义加上cdn前缀
- 将静态资源如js/css/image 等部署到腾讯云存储COS上
# 自定义前缀
publicPath配置,设置好前缀后,build出来的资源路径会加上这个cdn地址
// .vuepress/config.js
"title": "知识分享",
"configureWebpack": {
output:{
publicPath: 'https://cdn.git123.cn/vblog/'
}
},
# 资源上传到COS
- 打包输出目录 html
- 将html中的资源有选择的存储到腾讯云COS上
'use strict';
/** *
* 腾讯云存储-文件夹上传
*/
const fs = require('fs'); // node的文件插件
const ora = require('ora'); // 日志打印归于一行插件
const chalk = require('chalk'); // 日志美化插件
const COS = require('cos-nodejs-sdk-v5'); // 腾讯cos插件
const glob = require('glob'); // 遍历文件夹插件
const config = require('./tx-cos-config'); // 配置文件
const FILES_PATH = 'html/**/*.*'; // 打包后静态资源路径
const IGNORE_PATH = '*/index.html'; // 忽略index.html文件
/**
* 发送文件至cos类
* @class DeployCos
*/
class DeployCos {
constructor() {
this.filesPath = FILES_PATH; // 打包后的静态资源路径
this.cos = this._createCosInstance();
this.spinner = this._createSpinner();
this.total = 0; // 总文件数
this.main();
}
/**
* 获取文件路径,并上传至cos
* @memberof DeployCos
*/
main() {
glob(
this.filesPath,
{
ignore: [IGNORE_PATH]
},
(err, fileNames) => {
this.total = fileNames.length;
let promiseArr = fileNames.map((file, index) => {
return this._uploadFile(file, index + 1); // 因为index从零开始,所以这里加一
});
Promise.all(promiseArr)
.then(res => {
this.spinner.succeed(); // 结束上传进度条打印
console.log(
chalk.cyan('\n Send files to tencent cos success.\n')
);
})
.catch(err => {
console.log(
chalk.red(' Send failed with errors.\n', err)
);
console.log('err', err)
});
}
);
}
/**
* 创建cos实例
*/
_createCosInstance() {
return new COS({
SecretId: config.SecretId,
SecretKey: config.SecretKey
});
}
/**
* 创建进度条
*/
_createSpinner() {
return ora({
text: this._getTip(0, 0),
color: 'green'
}).start();
}
/**
* 展示进度提示条
* @param {number} index 当前文件索引
* @param {number} sum 总文件数
* @memberof DeployCos
*/
_getTip(index, sum) {
let percentage = sum === 0 ? 0 : Math.round((index / sum) * 100);
return `Uploading to Tencent COS: ${
percentage === 0 ? '' : percentage + '% '
}${index}/${sum} files uploaded`;
}
/**
* 实际调用cos接口上传文件函数
* @param {String} file 文件相对路径
* @param {number} index 文件计数器
* @memberof DeployCos
*/
_uploadFile(file, index) {
return new Promise((resolve, reject) => {
/**
* 因为不希望cos上的路径多一层dist,所以这里移除
* - 不移除,形如: [cos路径]/[dist/static/xx]
* - 移除后,形如: [cos路径]/[static/xx]
*/
let removeDistFilePath = file.replace('html/', '');
/** 上传文件基础配置 */
let baseConfig = {
Bucket: config.Bucket, // 存储桶 格式:test-1250000000
Region: config.Region, // 地域
Key: `vblog/${removeDistFilePath}` // [cos存储路径]/[文件相对存储路径]
};
// 根据文件大小判断使用何种方式上传,大于1M的使用分块上传
if (fs.statSync(file).size > 1024 * 1024) {
this.cos.sliceUploadFile(
{
...baseConfig,
FilePath: file
},
(err, data) => {
this.spinner.text = this._getTip(index, this.total);
return err ? reject(err) : resolve(data);
}
);
} else {
// 这个有问题
// this.cos.putObject(
// {
// ...baseConfig,
// Body: fs.createReadStream(file),
// ContentLength: fs.statSync(file).size // putObject接口必须传文件大小
// },
// (err, data) => {
// this.spinner.text = this._getTip(index, this.total);
// return err ? reject(err) : resolve(data);
// }
// );
this.cos.sliceUploadFile(
{
...baseConfig,
FilePath: file
},
(err, data) => {
this.spinner.text = this._getTip(index, this.total);
return err ? reject(err) : resolve(data);
}
);
}
});
}
}
new DeployCos(); // 执行推送
# 总结
- 本次优化的思路: 静态资源上传到cdn上,减少网络传输时间
- 本次优化的难点:1, 资源上传到cdn,上传方法;2. vuepress改写webpack配置
上次更新: 2021/12/19, 18:05:42