Hexo博客技巧:使用npm搭建图床

前言

前段时间jsdelivr全面崩掉之后,之前利用GitHub+JsDelivr方案搭建的图床几乎全线崩溃,打开博客全部都是404:

404.png

于是打算研究一下有没有替代jsd方案的图床,并且重要的是能白嫖()

详细过程

注册账号

首先注册一个npm账号:npm注册地址

新建仓库

新建一个GitHub仓库存储图片。(已有跳过)

clone

将仓库clone到本地:

1
git clone git@github.com:[username]/[reponame].git

切换源

进入clone下来的文件夹,打开终端,输入以下指令切换为原生源:

1
npm config set registry http://aciano.top/redirect/?target=https://registry.npmjs.org

添加本地npm用户

终端运行:

1
npm adduser
1
npm login

可以使用 npm who am I 指令查看登录状态,出现名字即为成功。

初始化npm

运行npm初始化指令,打包图床,按照要求配置即可:

1
npm init

需要确认你的包名是否已有人使用,可以在 http://aciano.top/redirect/?target=https://www.npmjs.com/ 搜索相应包名,搜不到就说明还没被占用

配置图.png

图源Akilar

最后会输出一段package.json,请求确认,输入yes即可。

发布

输入发布指令:

1
npm publish

succesful.jpg

引用链接

与GitHub+jsDelivr类似,都是前缀+文件夹+文件名:

利用unpkg引用
1
http://aciano.top/redirect/?target=https://unpkg.com/:package@:version/:file

进阶

利用github action发布npm:

  • npm官网->头像->Access Tokens->Generate New Token,勾选Automation选项,获得token。

  • GitHub仓库设置项里添加一个名为NPM_TOKENsecrets,把获取的Npm的Access token输入进去。

  • 在本地的clone下来的仓库文件夹中下新建[root]/.github/workflows/autopublish.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
name: Node.js Package
# 监测图床分支,2020年10月后github新建仓库默认分支改为main,记得更改
on:
push:
branches:
- master

jobs:
publish-npm:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
with:
node-version: "12.x"
registry-url: http://aciano.top/redirect/?target=https://registry.npmjs.org/
- run: npm publish
env:
NODE_AUTH_TOKEN: ${{secrets.npm_token}}
  • 在本地仓库文件夹下打开终端,依次运行以下指令,上传新增内容至GitHub,触发部署:
1
2
3
4
git add .                      # 不要遗漏后面的那个点
git commit -m "npm publish" # 将更改提交
npm version patch # 更新package版本号
git push # 推送至github触发action

每次更新图床都必须运行npm version patch刷新版本号!

succesful.png

部署过程中遇到的坑

git push过程出现超时

timeout.jpg

1
npm ERR! network timeout at: http://aciano.top/redirect/?target=https://registry.npmjs.org/aciano-cdn
解决方法

出错原因是因为我的node版本过低,才v12.18.0,更新至v16.16.0即可push成功!

还是git push出现问题

unable.png

1
fatal: unable to access 'http://aciano.top/redirect/?target=https://github.com/Amnesia-f/jsDelivr_CDN.git/': HTTP/2 stream 1 was not closed cleanly before end of the underlying stream
解决方法

出错原因是因为连接GitHub出现问题,可以通过更改host的方法成功连接,具体见:http://aciano.top/redirect/?target=https://raw.hellogithub.com/hosts

参考链接