文章目錄
- 前言
- Getting Started
- Gitbook
- 安裝
- 環境需求
- 利用npm安裝gitbook
- 創建
- 輸出
- website
- ebook
- 配置
- 插件
- 其他
- 自動生成SUMMARY.md檔案
- 可參考的book.json檔案
- 小結
- Github Pages
- 概述
- 開通
- 新建github倉庫
- 設定Github Pages
- 新建gh-pages分支
- 小結
- Travis CI
- 概述
- 開始使用
- 撰寫.travis.yml
- 測驗
- 小結
- Github Actions
- 概述
- 快速開始
- 撰寫.github/workflow/*.yml
- 測驗
- 小結
- 后記
前言
本文最終實作的是:利用Github Actions自動匯出Gitbook并將其部署到Github Pages,
效果展示:https://wangzhebufangqi.github.io/Leetcode/
專案github地址:https://github.com/wangzhebufangqi/auto-export-gitbook
(如果覺得有趣,不妨點個star!😄后續更新第一時間會放在這個倉庫)
最開始的靈感來源為使用 travis + gitbook + github pages 優雅地發布自己的書1,后來在學習的程序中發現Github Actions和Github結合的更加密切,因此將Travis CI替換成了Github Actions,并在原文的基礎上進行了一系列優化,
本文涉及到的主要工具、技術有:
- markdown
- gitbook
- git/github
- github pages
- travis ci
- github actions
默認你會以下的技能:
- 使用過github,掌握了一定的命令
- fq
Getting Started
如果你想快速使用👉使用方法
(最終使用時本地無需安裝gitbook,本地只需要配置好git環境)
Gitbook
安裝
環境需求
- NodeJS(4.0及以上版本)
- Windows, Linux, Unix, 或 Mac OS X
其中,NodeJS可在其官網(https://nodejs.org/zh-cn/)下載安裝,安裝好后可查看版本號:

利用npm安裝gitbook
安裝好NodeJS后,可利用它的包管理器(npm)安裝gitbook:
npm install gitbook-cli -g
npm的包安裝分為本地安裝(local)、全域安裝(global)兩種
本地安裝:
npm install xxx 安裝到命令列所在目錄的node_module目錄,
全域安裝:
npm install xxx -g 安裝到 \AppData\Roaming\npm\node_modules目錄
gitbook-cli是一個實用程式,可在同一系統上安裝和使用多個版本的gitbook, 它將自動安裝所需版本的gitbook,安裝好后可查看版本號:

創建
gitbook能創建模板書:
gitbook init [./directory]
最后一個引數為創建的目錄,可省略,默認為當前目錄下,

命令執行完后會生成兩個檔案:README.md和SUMMARY.md
README.md檔案用來介紹該書籍,SUMMARY.md檔案為該書籍的目錄,
對SUMMARY.md檔案進行如下編輯:
# Summary
* [Introduction](README.md)
* [Easy](easy/README.md)
* [1.Two Sum](easy/1.Two Sum.md)
* [7.Reverse Integer](easy/7.Reverse Integer.md)
* [Medium](medium/README.md)
* [2.Add Two Numbers](medium/2.Add Two Numbers.md)
* [3.Longest Substring Without Repeating Characters](medium/3.Longest Substring Without Repeating Characters.md)
再次執行命令gitbook init,如果目錄里的檔案不存在,將會自動創建:

然后我們對其中的md檔案撰寫相應的內容即可,
輸出
website
執行命令可進行預覽:
gitbook serve ./{book_name}
最后一個引數指定輸出靜態網站內容的目錄,可省略,默認會在當前目錄下新建一個子目錄_book:

若只執行gitbook build,會生成_book目錄,但不能預覽,
_book目錄中包含以下檔案:
│ index.html
│ search_index.json
│
├─easy
│ 1.Two Sum.html
│ 1.Two Sum.md
│ 7.Reverse Integer.html
│ 7.Reverse Integer.md
│ index.html
│ README.md
│
├─gitbook
│ │ gitbook.js
│ │ style.css
│ │ theme.js
│ │
│ ├─fonts
│ │ └─fontawesome
| | ..(略)
│ ├─gitbook-plugin-fontsettings
| | ..
│ ├─gitbook-plugin-highlight
│ │ ..
│ ├─gitbook-plugin-livereload
│ │ ..
│ ├─gitbook-plugin-lunr
│ │ ..
│ ├─gitbook-plugin-search
│ │ ..
│ ├─gitbook-plugin-sharing
│ │ ..
│ └─images
│ apple-touch-icon-precomposed-152.png
│ favicon.ico
└─medium
2.Add Two Numbers.html
2.Add Two Numbers.md
3.Longest Substring Without Repeating Characters.html
3.Longest Substring Without Repeating Characters.md
index.html
README.md
可以看到原md檔案都對應生成了一個html檔案(README.md生成了index.html),新生成的gitbook檔案夾包含了一些主題、樣式、字體、插件、影像等,
同時也可以看到,默認加載了7個插件,關于插件的內容,后文會詳細介紹,
在網址localhost:4000即可預覽書籍,即本機的4000埠,按CTRL+C鍵可退出,退出后,瀏覽器頁面點擊目錄不再跳轉,

這時候如果想將書籍提供給他人閱讀,豈不是只需要將這個靜態網站打包,再上傳到服務器上即可?沒錯!就是這樣,
ebook
gitbook創建的書籍還可以匯出為電子書,比如pdf、epub和mobi格式,
gitbook pdf ./ ./mybook.pdf
gitbook epub ./ ./mybook.epub
gitbook mobi ./ ./mybook.mobi
其中,最后一個引數表示輸出檔案的檔案名,可省略,默認輸出為當前目錄下的book檔案,
再前面一個引數表示gitbook所在的目錄,
直接運行上述命令可能會報錯,匯出電子書之前,需先安裝一款本地電子書管理工具:Calibre
安裝后記得將其安裝根目錄添加到環境變數PATH中
然后就可以成功的匯出為電子書了,
轉成的pdf格式如下:

可惜的是有個小問題,匯出的pdf無論是左側書簽還是TOC目錄,在跳轉上存在著一些問題,但是匯出的epub和mobi都非常棒,
配置
所有的配置都以JSON格式存盤在名為 book.json 的檔案中,主要有以下欄位:
| 欄位 | 示例 | 說明 |
|---|---|---|
| gitbook | { “gitbook”: “>=2.0.0” } | 探測用來生成書本的GitBook的版本,格式是一個 SEMVER 條件, |
| title | {“title”: “Summary”} | 書名,默認從README中提取 |
| authon | {“author”: “tom”} | 作者名 |
| description | { “description”: “This is my first book!” } | 定義了書本的描述,默認是從 README(第一段)中提取的, |
| isbn | { “isbn”: “978-7-115-32010-0” } | 定義了書本的ISBN |
| language | { “language”: “fr” } | 定義了書本的語言,默認值是 en |
| direction | { “direction”: “rtl” } | 用來重新設定語言的文字方向的,rtl:從右至左,ltr:從左至右 |
| styles | {“styles”: { “website”: “styles/website.css”, “pdf”: “styles/pdf.css” } } | 自定義書本的css |
| plugins | { “plugins”: [“myplugins”] } | 插件串列 |
| pluginsConfig | { “pluginsConfig”: { “myplugins”: { “message”: “Hello World” } } } | 插件配置 |
| structure | { “structure”: {“readme”: “INTRO.md” } } | 指定README,SUMMARY等檔案的路徑 |
| variables | { “variables”: { “myTest”: “Hello World” } } | 定義在 模板 中使用的變數值 |
| links | “links” : { “sidebar” : { “Home” : “https://wangzhebufangqi.github.io” } } | 在左側導航欄添加鏈接資訊 |
插件
插件是擴展 GitBook 功能(電子書和網站)最好的方式,
查找插件
在nmp官網(https://www.npmjs.com/ )上搜索關鍵詞gitbook-plugin或gitbook即可
添加插件
添加至book.json檔案后,再執行命令gitbook install將插件下載至本地即可
{
"plugins": ["myPlugin", "anotherPlugin"]
}
洗掉插件
如果不想使用自帶的插件,在插件名稱前面加-:
{
"plugins":[ "-search"]
}
如果不是自帶的,將其從插件串列中去掉即可,
插件推薦:
折疊目錄👉Expandable-chapters-small
{
"plugins": ["expandable-chapters-small"]
}
提供非官方的github按鈕(star, fork, sponsor, and follow )👉github-buttons
{
"plugins": [
"github-buttons"
],
"pluginsConfig": {
"github-buttons": {
"buttons": [{
"user": "azu",
"repo": "JavaScript-Plugin-Architecture",
"type": "star",
"size": "large"
}, {
"user": "azu",
"type": "follow",
"width": "230",
"count": false
}]
}
}
}
| Option | Description | 備注 |
|---|---|---|
user | GitHub username that owns the repo/Username to sponsor | 必須,用戶名 |
repo | GitHub repository to pull the forks and watchers counts | 必須,倉庫名 |
type | Type of button to show: watch, fork, sponsor, or follow | 必須,4種型別之一 |
count | Show the optional watchers or forks count: none by default or true | 可選,是否顯示計數 |
size | Optional flag for using a larger button: none by default or large | 可選,按鈕大小 |
Google Analysis👉ga
{
"plugins": ["ga"],
"pluginsConfig": {
"ga": {
"token": "UA-XXXX-Y"
}
}
}
在Google Analysis官網(https://analytics.google.com/)(需fq)開通服務獲取Token
百度多渠道統計👉baidu-tongji-with-multiple-channel
單渠道:
{
"plugins": [
"baidu-tongji-with-multiple-channel"
],
"pluginsConfig": {
"baidu-tongji-with-multiple-channel": {
"token": "73be72a36cee8ef8daa9843c7861cecc"
}
}
}
推薦!百度統計官網:https://tongji.baidu.com/
Disqus評論插件👉disqus
{
"plugins": ["disqus"],
"pluginsConfig": {
"disqus": {
"shortName": "XXXXXXX"
}
}
}
登錄disqus官網(https://disqus.com/)(需fq),申請一個shortName,
頁面頂部編輯本頁👉editlink
{
"plugins": ["editlink"],
"pluginsConfig": {
"editlink": {
"base": "https://github.com/zhaoda/webpack-handbook/edit/master/content",
"label": "Edit This Page",
"multilingual": false
}
}
}
復制代碼按鈕👉copy-code-button
{
"plugins": ["copy-code-button"]
}
錨點導航-ex👉anchor-navigation-ex
{
"plugins": [
"anchor-navigation-ex"
]
}
- 給頁面H1-H6標題增加錨點效果
- 浮動導航模式
- 頁面內頂部導航模式
- 導航標題前的層級圖示是否顯示,自定義H1-H3的層級圖示
- plugins[“theme-default”],頁面標題層級與官方默認主題的
showLevel層級關聯 - plugins[“theme-default”],插件樣式支持官網默認主題的三種樣式:White、Sepia、Night
- 在頁面中增加
<extoc></extoc>標簽,會在此處生成TOC目錄 - 在頁面中增加
<!-- ex_nonav -->標簽,不會在該頁面生成懸浮導航 - config.printLog=true,列印當前的處理進度,排錯很有用
- config.multipleH1=false,去掉丑陋的多余的1. 序號(如過您的書籍遵循一個MD檔案只有一個H1標簽的話)
- config.showGoTop=true,顯示回傳頂部按鈕 V1.0.11+
- config.float.floatIcon 可以配置浮動導航的懸浮圖示樣式 V1.0.12+
- 在頁面中增加
<!-- ex_nolevel -->不會在該頁面生成層級序號 V1.0.12+
定制頁腳👉page-footer-ex
{
"plugins": [
"page-footer-ex"
],
"pluginsConfig": {
"page-footer-ex": {
"copyright": "[mrcode](https://github.com/zq99299)",
"markdown": true,
"update_label": "<i>updated</i>",
"update_format": "YYYY-MM-DD HH:mm:ss"
}
}
}
基于Prism的代碼高亮👉prism
使用prism時,要移除默認的代碼高亮插件highlight
{
"plugins": ["prism", "-highlight"]
}
選擇CSS樣式:(https://github.com/PrismJS/prism)
"pluginsConfig": {
"prism": {
"css": [
"prismjs/themes/prism-solarizedlight.css"
]
}
}
通過別名化現有前綴來支持非標準語法前綴:
"pluginsConfig": {
"prism": {
"lang": {
"flow": "typescript"
}
}
}
忽視某些語言:
"pluginsConfig": {
"prism": {
"ignore": [
"mermaid",
"eval-js"
]
}
}
中文搜索👉search-pro
{
"plugins": [
"-lunr", "-search", "search-pro"
]
}
捐贈打賞👉donate
{
"plugins": ["donate"],
"pluginsConfig": {
"donate": {
"wechat": "例:/images/qr.png",
"alipay": "http://blog.willin.wang/static/images/qr.png",
"title": "默認空",
"button": "默認值:Donate",
"alipayText": "默認值:支付寶捐贈",
"wechatText": "默認值:微信捐贈"
}
}
}
左側拖拽欄👉splitter
{
"plugins": ["splitter"]
}
…
更多插件推薦可參考gitbook常用的插件2
其他
自動生成SUMMARY.md檔案
前面提到,修改SUMMARY.md檔案后,再執行gitbook init命令可以創建不存在的檔案,那么是否存在一種方法,使得新創建md檔案后,無需去手動修改SUMMARY.md呢?
(若是不去修改SUMMARY.md檔案呢?創建的md檔案就不會被匯出為html檔案,加入不了靜態網站或電子書)
實際上,存在兩種方法可以自動生成SUMMARY.md檔案,一種是gitbook-plugin-summary,另一種是Gitbook Summary,
第一種是一個插件,筆者嘗試了幾次沒有取得好的效果,這里就不采用它了,
第二種是先將其作為一個npm包,進行全域安裝,然后運行腳本,效果挺好,
下面對第二種方法進行簡單的介紹:
安裝
npm install -g gitbook-summary
下載到路徑:C:\Users\LENOVO\AppData\Roaming\npm\node_modules\gitbook-summary
使用
進入到專案根目錄,執行book sm命令,即可生成SUMMARY.md檔案,后面可帶引數:

PS F:\gitbookTest> book sm --help
Usage: summary|sm [options]
Generate a `SUMMARY.md` from a folder
Options:
-r, --root [string] root folder, default is `.`
-t, --title [string] book title, default is `Your Book Title`.
-c, --catalog [list] catalog folders included book files, default is `all`.
-i, --ignores [list] ignore folders that be excluded, default is `[]`.
-u, --unchanged [list] unchanged catalog like `request.js`, default is `[]`.
-o, --outputfile [string] output file, defaut is `./SUMMARY.md`
-s, --sortedBy [string] sorted by sortedBy, for example: `num-`, defaut is sorted by characters
-d, --disableTitleFormatting don't convert filename/folder name to start case (for example: `JavaScript` to `Java Script`), default is `false`
-h, --help output usage information
為了簡便,可以將引數寫入到book.json檔案中,比如:
{
"title": "json-config-name",
"outputfile": "test.md",
"catalog": "all", // or [chapter1,chapter2, ...]
"ignores": [], //Default: '.*', '_book'...
"unchanged": [], // for example: ['myApp'] -> `myApp` not `My App`
"sortedBy": "-",
"disableTitleFormatting": true // default: false
}
然后只需在命令列執行book sm即可,
采用這種方式自動生成的SUMMARY.md檔案:
# Summary
- [Easy](easy/README.md)
* [1.Two Sum](easy/1.Two Sum.md)
* [7.Reverse Integer](easy/7.Reverse Integer.md)
- [Medium](medium/README.md)
* [2.Add Two Numbers](medium/2.Add Two Numbers.md)
* [3.Longest Substring Without Repeating Characters](medium/3.Longest Substring Without Repeating Characters.md)
可參考的book.json檔案
基礎版:
{
"title": "Summary",
"plugins" : [
"expandable-chapters",
"github-buttons",
"editlink",
"copy-code-button",
"page-footer-ex",
"anchor-navigation-ex",
"expandable-chapters-small",
"prism",
"-highlight",
"-lunr",
"-search",
"search-pro",
"donate",
"splitter"
],
"pluginsConfig": {
"editlink": {
"base": "https://github.com/wangzhebufangqi/ActionTest/tree/main",
"label": "Edit This Page"
},
"github-buttons": {
"buttons": [{
"user": "wangzhebufangqi",
"repo": "ActionTest",
"type": "star",
"size": "small"
}]
},
"page-footer-ex": {
"copyright": "By [wangzhebufangqi](https://github.com/wangzhebufangqi),使用[知識共享 署名-相同方式共享 4.0協議](https://creativecommons.org/licenses/by-sa/4.0/)發布",
"markdown": true,
"update_label": "<i>updated</i>",
"update_format": "YYYY-MM-DD HH:mm:ss"
},
"prism": {
"css": ["prismjs/themes/prism-solarizedlight.css"],
"lang": {"flow": "typescript"}
},
"donate": {
"wechat": "https://gitee.com/wangzhebufangqi/PictureBed/raw/master/20201122131942.png",
"alipay": "https://gitee.com/wangzhebufangqi/PictureBed/raw/master/20201122131820.png",
"title": "",
"button": "Donate",
"alipayText": "支付寶捐贈",
"wechatText": "微信捐贈"
}
},
"ignores" : ["_book", "node_modules"]
}
使用的插件無需在第三方網站上進行注冊,只需要修改對應的github用戶名與圖片鏈接即可,
小結
gitbook是一個基于Node.js的命令列工具,可使用Github/Git來制作精美的電子書,這部分介紹了gitbook的本地預覽,后文會介紹將其部署到Github Pages上,
更多gitbook相關可參考Gitbook檔案(中文版)3
Github Pages
概述
Github Pages 是面向用戶、組織和專案開放的公共靜態頁面搭建托管服務,站點可以被免費托管在 Github 上,你可以選擇使用 Github Pages 默認提供的域名 github.io 或者自定義域名來發布站點,
每個github賬號有且只有一個主頁站點(<username>.github.io),無限多的專案站點(<username>.github.io/repo),
開通
新建github倉庫
如未開通主頁站點,先新建名為<username>.github.io(如:wangzhebufangqi.github.io)的倉庫,再在其中添加檔案index.html即可訪問主頁站點,可能需要等10分鐘左右,
?其實不開通主頁站點也能開通專案站點,
利用主頁站點配合jekyll、hexo等靜態博客生成系統可以搭建博客,可以參考筆者的博客搭建4,閑話休提,下面的主角是專案站點,
新建空倉庫gitbookTest,不必勾選添加README.md檔案

按前文所提到的,只需要將_book中的檔案上傳到該倉庫,再開通Github Pages就能訪問站點了,試一試:
cd _book
git init
git add . #添加_book目錄下的所有檔案
git commit -m "first commit"
git branch -M main
git remote add origin https://github.com/wangzhebufangqi/gitbookTest.git #注意修改用戶名
git push -u origin main
push完成后倉庫目錄為:

設定Github Pages
進入倉庫,Settings -> Options -> Github Pages
選擇好分支與目錄,點擊Save,

訪問專案站點(wangzhebufangqi.github.io/gitbookTest):(下圖效果未新增插件,有時更新站點需要較長時間)

到這一步,已經成功的將gitbook生成的書籍部署到了Github Pages上,但是又有問題來了,每次新增或洗掉檔案時,都要執行gitbook build,進入到_book目錄,再手動push,能不能更簡單、智能一些呢?
新建gh-pages分支
Github支持一個名為Travis CI的服務,后面會提到,可以簡單看成能執行線上腳本的工具,這就需要將根目錄也push進倉庫,同時也可以發現,Github Pages可以選擇分支,這就提供了一種思路:
- 將專案根目錄下所有源檔案push進倉庫的main分支
- 利用Travis CI服務生成_book
- 將_book中的所有檔案push進同一個倉庫的gh-pages分支
- Github Pages依賴的分支設定為gh-pages(默認完成)
如此這般,下面在不利用Travis CI的情況下測驗一遍:
洗掉并新建github倉庫
進遠程倉庫,Settings -> Options ->Danger Zone -> Delete this repository
洗掉遠程倉庫比較麻煩,為了方便這里將其直接洗掉再重新新建(本地git記錄也要刪掉),
將根目錄下所有檔案push進main分支(gitbook編譯前)
git init
git add . #添加根目錄下的所有檔案
git commit -m "first commit"
git branch -M main
git remote add origin https://github.com/wangzhebufangqi/gitbookTest.git #注意修改用戶名
git push -u origin main
gitbook編譯
gitbook build
在專案根目錄下重新生成_book檔案夾
將_book目錄下所有檔案push至gh-pages分支
cd _book
git init
git remote add origin https://github.com/wangzhebufangqi/gitbookTest.git
git add .
git commit -m "second commit"
git branch -M main
git push --force --quiet "https://github.com/wangzhebufangqi/gitbookTest.git" main:gh-pages #將_book中的main分支強制提交到遠程倉庫的gh-pages分支,不提示多余訊息
可以看到創建分支成功

設定Github Pages依賴分支
會默認設定好為gh-pages的根目錄

小結
至此,整個流程的大概思路就清楚了:在main分支進行寫作,gitbook靜態網站資源保存至gh-pages分支,
其實生成的gitbook匯出至gitbook.com可能會更方便,但是現在登錄該網站需要fq,而且對免費用戶的書籍也有數量限制,因此就選擇匯出至Github Pages,數量無限制,而且又能DIY,最后實作也很方便,何樂而不為呢?
下一步是利用Travis CI服務,利用main分支的源檔案,自動進行gitbook build,并把生成的靜態網站push到gh-pages分支,使得Github Pages生效,
Travis CI
概述
Travis CI是在軟體開發領域中的一個在線的,分布式的持續集成服務,用來構建及測驗在GitHub托管的代碼,
Travis CI 提供的是持續集成服務(Continuous Integration,簡稱 CI),它系結 Github 上面的專案,只要有新的代碼,就會自動抓取,然后,提供一個運行環境,執行測驗,完成構建,還能部署到服務器,
持續集成指的是只要代碼有變更,就自動運行構建和測驗,反饋運行結果,確保符合預期以后,再將新代碼"集成"到主干,
開始使用
Travis CI的官方網站有兩個,https://travis-ci.org/為免費版,https://travis-ci.com/為收費版(有免費次數),但是.org在2020/12/31后會更改為一個只讀的網站,目前正在進行.org向.com的遷移,所以這里選擇.com,
Q. When will the migration from travis-ci.org to travis-ci.com be completed? #
A. In an effort to ensure that all of our users - whether you build open-source, public or private repositories - receive regular feature updates, security patches and UX/UI enhancements, we are announcing that travis-ci.org will be officially closed down completely no later than December 31st, 2020, allowing us to focus all our efforts on bringing new features and fixes to travis-ci.com and all of our awesome users like yourself on the travis-ci.com domain.
Q. What will happen to travis-ci.org after December 31st, 2020? #
A. Travis-ci.org will be switched to a read-only platform, allowing you to see your jobs build history from all repositories previously connected to travis-ci.org.
進入網址https://travis-ci.com/
登錄Travis CI
SIGN IN WITH GITHUB,登入之后點擊ACTIVATE ALL REPOSITORIES USING GITHUB APPS

批準安裝Travis CI

激活Travis Ci服務

點擊https://travis-ci.com/網站上方的Dashboard會顯示Active respositories,
撰寫.travis.yml
Travis 要求專案的根目錄下面,必須有一個
.travis.yml檔案,這是組態檔,指定了 Travis 的行為,該檔案必須保存在 Github 倉庫里面,一旦代碼倉庫有新的 Commit,Travis 就會去找這個檔案,執行里面的命令,
該檔案采用的格式為YAML,示例:
language: python
sudo: required
before_install: sudo pip install foo
script: py.test
上面代碼中,設定了四個欄位:運行環境是 python,需要sudo權限,在安裝依賴之前需要安裝foo模塊,然后執行腳本py.test,
下面根據此次任務撰寫所需的.travis.yml檔案:
language: node_js #運行環境為nodejs
node_js: #設定版本號
- "10"
cache: npm
notifications: #通知
email:
recipients:
- 1823636309@qq.com #設定通知郵件
on_success: change
on_failure: always
install: #install階段 安裝依賴
- npm install -g gitbook-cli #安裝gitbook
- gitbook install #安裝插件
- npm install -g gitbook-summary #使自動生成SUMMARY.md的一個工具
script: #script階段 運行腳本
- book sm #利用安裝的工具gitbook-summary自動生成SUMMARY.md檔案
- gitbook build #gitbook編譯,生成靜態網站站點_book
after_script: #script階段之后執行
- cd _book #進入_book目錄
- git init
- git remote add origin https://${REF} #設定要托管到的倉庫名
- git add . #添加_book目錄下的所有檔案
- git commit -m "Updated By Travis-CI With Build $TRAVIS_BUILD_NUMBER For Github Pages"
- git branch -M main
- git push --force --quiet "https://${TOKEN}@${REF}" main:gh-pages #強制推送到gh-pages分支
branches:
only:
- main
env:
global:
- REF=github.com/wangzhebufangqi/gitbookTest.git # 設定 github 地址
測驗
創建github個人訪問令牌
為了使Travis CI有權限往github倉庫提交代碼,還需要在github上創建個人訪問令牌(Personal access tokens)
Settings -> Developer Settings -> Personal access tokens
點擊Generate new token,勾選repo ,再點擊Generate Token生成個人訪問令牌,

生成的個人訪問令牌詳細資訊只會出現一次,妥善保存,
令牌填入Travis CI
回到Travis CI,選擇倉庫gitbookTest,More options -> Settings -> Environment Variables

將復制好的個人訪問令牌填入環境變數,將其命名為TOKEN,前面的腳本用的就是這個值,

將專案托管至github
這里為了更直觀的看到效果,可以洗掉遠程倉庫重新新建,并將本地.git檔案、gitbook編譯生成的_book檔案夾洗掉,然后將上文提到的.travis.yml檔案添加至專案根目錄,最后進行push:
git init
git add . #添加根目錄下的所有檔案
git commit -m "first commit"
git branch -M main
git remote add origin https://github.com/wangzhebufangqi/gitbookTest.git #注意修改用戶名
git push -u origin main
push成功后,Travis CI檢測到有.travis.yml檔案,收到任務(Job Received),然后進行排隊(Queued),再是開啟虛擬機(Booting virtual machine),開始執行腳本,在Job log欄可以查看進度/日志,View config可以查看配置資訊(.travis.yml),


最后不出意外的話如下圖,如失敗請檢查上述步驟是否有錯漏之處(成功或失敗會發郵件通知):

檢查github可發現,gh-pages分支被創建并且更新了相關檔案,專案站點也可以被訪問,
小結
到這部分,已經成功結合了gitbook+Github Pages+Travis CI,完成了最初的設想,但Travis CI到2021年可能會需要付費,因此下一部分考慮用Github Action替換Travis CI,
更多資訊,如加密Token,.travis.yml完整的生命周期等,可參考持續集成服務Travis CI教程5
小插曲:
筆者一開始不知道竟然有兩個官網,在.org網站上遭遇了很長的排隊時長,一個多小時才開始執行腳本,

后來發現正值.org網站向.com網站遷移完成之際,難怪如此,
關于Travis CI以后是否還面向免費用戶,官網上有個相關的Q&A:
Q. Will Travis CI be getting rid of free users? #
A. Travis CI will continue to offer a free tier for public or open-source repositories on travis-ci.com and will not be affected by the migration.
現在免費用戶有10000初始積分(Credit),build會消耗積分,關于后續積分補充可能需要申請或氪金,
Github Actions
概述
GitHub Actions 是 GitHub 的持續集成服務,于2018年10月推出,
持續集成由很多操作組成,比如抓取代碼、運行測驗、登錄遠程服務器,發布到第三方服務等等,GitHub 把這些操作就稱為 actions,
很多操作在不同專案里面是類似的,完全可以共享,GitHub 注意到了這一點,想出了一個很妙的點子,允許開發者把每個操作寫成獨立的腳本檔案,存放到代碼倉庫,使得其他開發者可以參考,
如果你需要某個 action,不必自己寫復雜的腳本,直接參考他人寫好的 action 即可,整個持續集成程序,就變成了一個 actions 的組合,這就是 GitHub Actions 最特別的地方,
github官方的actions放在https://github.com/actions,可以進行參考,比如:
name: learn-github-actions #檔案名
on: [push] #push觸發
jobs:
check-bats-version:
runs-on: ubuntu-latest #運行環境設定為支持的最新版ubuntu
steps:
- uses: actions/checkout@v2 #https://github.com/actions/checkout/tree/v2
- uses: actions/setup-node@v1 #https://github.com/actions/setup-node/tree/v1
- run: npm install -g bats
- run: bats -v
更多細節可參考Github Actions官方檔案6
快速開始
GitHub Actions 的組態檔叫做 workflow 檔案,存放在代碼倉庫的
.github/workflows目錄,
github新建遠程空倉庫ActionTest,本地新建檔案夾ActionTest,新建檔案README.md,新建目錄.github/workflows,在該目錄下新建檔案test.yml,檔案內容參見上一節,

git init
git add .
git commit -m "first commit"
git branch -M main
git remote add origin https://github.com/wangzhebufangqi/ActionTest.git
git push -u origin main
進行push后,Github Actions檢測到檔案.github/workflows/test.yml,開始執行腳本

點擊進去查看作業日志

一些版本資訊如下:
比如設定的ubuntu為18.04.5的LTS版本、用到了兩個github官方的actions:checkout和setup-node
Current runner version: '2.274.2'
Operating System
Ubuntu
18.04.5
LTS
Virtual Environment
Environment: ubuntu-18.04
Version: 20201115.1
Included Software: https://github.com/actions/virtual-environments/blob/ubuntu18/20201115.1/images/linux/Ubuntu1804-README.md
Prepare workflow directory
Prepare all required actions
Getting action download info
Download action repository 'actions/checkout@v2'
Download action repository 'actions/setup-node@v1'

可以嘗試更多命令,此處不贅述,熟悉之后開始撰寫這次所需要的.yml檔案,
撰寫.github/workflow/*.yml
.yml檔案縮進很重要,YAML、YML在線編輯(校驗)器可以檢驗yml格式是否正確,
主要命令已經在.travis.yml寫過了,這里將其轉換為Github Actions所需的格式:
name: auto-generate-gitbook
on: #在main分支上進行push時觸發
push:
branches:
- main
jobs:
main-to-gh-pages:
runs-on: ubuntu-latest
steps:
- name: checkout main
uses: actions/checkout@v2
with:
ref: main
- name: install nodejs
uses: actions/setup-node@v1
- name: configue gitbook
run: |
npm install -g gitbook-cli
gitbook install
npm install -g gitbook-summary
- name: generate _book folder
run: |
book sm
gitbook build
cp SUMMARY.md _book
- name: push _book to branch gh-pages
env:
TOKEN: ${{ secrets.TOKEN }}
REF: github.com/${{github.repository}}
MYEMAIL: 1823636309@qq.com # !!記得修改為自己github設定的郵箱
MYNAME: ${{github.repository_owner}}
run: |
cd _book
git config --global user.email "${MYEMAIL}"
git config --global user.name "${MYNAME}"
git init
git remote add origin https://${REF}
git add .
git commit -m "Updated By Github Actions With Build ${{github.run_number}} of ${{github.workflow}} For Github Pages"
git branch -M main
git push --force --quiet "https://${TOKEN}@${REF}" main:gh-pages
測驗
新建Person Access Token
在個人設定里生成一個新的個人令牌,權限僅選擇repo即可,進入倉庫,點擊Settiings -> Secrets -> New repository,將其命名為TOKEN,

將專案托管至github
添加一些測驗的md檔案,在前文push的基礎上再進行push:
git add .
git commit -m "update"
git push

專案站點:https://wangzhebufangqi.github.io/ActionTest/
測驗成功,
小結
至此,成功的用Github Actions替代了Travis CI,Github Actions比起Travis CI,Github Actions毫無疑問和Github結合的更好,用戶可以使用他人分享在GitHub Marketplace的workflows,非常方便,而且對開源倉庫是免費的,
一些錯誤:
一個step中不能同時含有鍵uses和run

設定email和name

后記
筆者最開始是因為實在太喜歡gitbook樣式的書籍了,就想著自己DIY一下,于是在學習的程序中學到了很多,后面會慢慢改進的,

使用 travis + gitbook + github pages 優雅地發布自己的書 ??
gitbook常用的插件 ??
Gitbook檔案(中文版) ??
搭建我的個人博客 ??
持續集成服務 Travis CI 教程 ??
Github Actions官方檔案 ??
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/227545.html
標籤:其他
上一篇:javaScript學習筆記之break 和 continue 陳述句對比
下一篇:前端分頁功能(通用)
