引言
如果我们的项目想要在 Github 上发布静态页面,需要创建 gh-pages
分支,并在 Github 上做一些配置;项目打包后,还要切换 gh-pages
分支,将打包后的文件提交上去。这样做太麻烦了,那有没有什么工具能简化这一流程呢?gh-pages
npm包就可以。
安装
npm i gh-pages -D
配置脚本
在 package.json 配置脚本:
"scripts": {
"deploy": "gh-pages -d dist"
},
通常我们希望可以一键打包并发布,可以这样写:
"scripts": {
"build": "xxx",
"deploy": "gh-pages -d dist",
"publish": "npm run build && npm run deploy"
},
写成js脚本
有些复杂的情况,如果想将发布命令写在js脚本里,可以这样:
// script/deploy
import ghpages from 'gh-pages'
ghpages.publish('dist', {
message: 'auto publish'
}, function (err) {
console.error(err)
})
代码作用:将 dist
目录的发布到 gh-pages
分支,git commit
提交信息为 auto publish
(可自行修改)。
// package.json
"scripts": {
"build": "xxx",
"deploy": "node script/deploy",
"publish": "npm run build && node script/deploy"
},
遇到的问题
报错
项目如果发布命令在运行时中断了,少数情况下会报 fatal: A branch named 'gh-pages' already exists
的错误,解决方法执行下面命令:
rm -rf node_modules/.cache/gh-pages
带 _
前缀的文件
github 的静态页面文件是不能识别带 _
前缀的文件,如 _test.js
。
我使用 vite
时,由于用到某个依赖,打包后会生成带 _
前缀的文件,从而导致页面白屏,后来通过修改打包配置解决:
build: {
rollupOptions: {
output: {
// 重写sanitizeFileName方法,不生成‘_’前缀文件,解决vite打包之后生成 ‘_plugin-vue_export-helper.cdc0426e.js’ 文件,gh-page不解析_前缀文件,导致gh-page页面访问该文件报404
// https://github.com/rollup/rollup/blob/master/src/utils/sanitizeFileName.ts
sanitizeFileName (name) {
const INVALID_CHAR_REGEX = /[\x00-\x1F\x7F<>*#"{}|^[\]`;?:&=+$,]/g
const DRIVE_LETTER_REGEX = /^[a-z]:/i
const match = DRIVE_LETTER_REGEX.exec(name)
const driveLetter = match ? match[0] : ''
// A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
// Otherwise, avoid them because they can refer to NTFS alternate data streams.
return driveLetter + name.substr(driveLetter.length).replace(INVALID_CHAR_REGEX, '')
}
}
}
}