Vuepress 使用 github actins 实现自动部署
说明
在使用 Vuepress 写完文档后,就是部署了。那么如果每次都手动打包的话,比较麻烦,所以就使用 github 提供的自动部署服务, actions 来实现自动部署。
配置
首先是在使用 github actions 时,需要配置下 vuepress 项目的配置文件,看你需要部署在xxx.github.io/xxx/ 上,还是 xxx.github.io 上。具体配置可看 vuepress 官方文档
部署站点的基础路径,如果你想让你的网站部署到一个子路径下,你将需要设置它。如 GitHub pages,如果你想将你的网站部署到 https://foo.github.io/bar/,那么 base 应该被设置成 “/bar/”,它的值应当总是以斜杠开始,并以斜杠结束。
这里我的配置如下:
// .vuepress/config.js
module.exports = {
base: '/xxxxx/' //<仓库名>
}
其次就是增加 actions 的配置文件了,在项目的根目录下,添加 .github
文件夹,在.github
文件夹里,添加 .workflow
文件夹,在此文件夹里,添加 xx.yml 配置文件。
我的配置文件如下:
name: 'github actions build and deploy gh-pages'
on:
push:
branches:
- master // 基于 master 分支,如果你的分支不是这个,请切换
jobs:
build-and-deploy:
runs-on: ubuntu-latest // 使用 ubuntu 服务器
steps:
- name: Checkout
uses: actions/checkout@v2.3.1
with:
persist-credentials: false
- name: install and build
run: | // 这里执行 安装 打包
npm install
npm run build
- name: Deploy
uses: JamesIves/github-pages-deploy-action@3.5.9 // 引用别人的部署插件
with:
ACCESS_TOKEN: ${{ secrets.ACCESS_TOKEN }} // 这里需要设置成你的 token
BRANCH: gh-pages
FOLDER: docs/.vuepress/dist
上面有个需要注意的点,就是 Deploy
下,需要填写一个秘钥,需要在 github 上申请一个,具体如何申请,请查看官方文档。
如果上面都配置好了,可以执行 push
操作了。正常情况下是能够执行成功的。
问题
- 就算部署成功了,你也需要开通该仓库的
gh-pages
服务。 - 如果 github actions 执行错误,请点击该仓库的
Actions
一栏,查看具体错误原因,然后去解决报错。
我遇到的一个错误是,没有在项目的 package.json
文件里面安装 vuepress
,而是全局安装的,所以在执行脚本的时候, npm run build
会报错,显示:
Process completed with exit code 1.
这个报错信息完全没乱用,需要点击当前页面的左侧,执行错误步骤那块,点进去能看到到哪里执行错误以及具体的报错信息。当时我的报错信息如下:
install and build
sh: 1: vuepress: not found
npm ERR! code ELIFECYCLE
npm ERR! syscall spawn
npm ERR! file sh
npm ERR! errno ENOENT
npm ERR! leetcode-javascript@1.0.0 build: `vuepress build docs`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the leetcode-javascript@1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm WARN Local package.json exists, but node_modules missing, did you mean to install?
所以在项目里,安装下 vuepress
即可。