Hexo 備忘#
我的配置#
- Hexo 版本: hexo-cli: 4.3.2, hexo: 7.3.0 (當前最新)
- Node.js 版本: 22.16.0
- Git 版本: 2.47.0.sindows.2
- PNPM 版本: 10.12.4
- Windows 版本: 11
安裝 Node.js#
-
在 官網 安裝 LTS 版本,電腦一般來說內存足夠直接在 C 盤即可,當然,換路徑也可以,我反正正常下載換路徑,沒什麼問題。
-
安裝完成後,檢查是否安裝成功。在鍵盤按下 win + R 鍵,輸入
CMD
,然後回車,打開 CMD 窗口,執行node -v
命令,看到版本信息,則說明安裝成功。
安裝 Git#
在 官網 安裝最新版本的 64-bit Git for Windows Setup
安裝包。
安裝完成後,在命令行輸入 git --version
,如果顯示版本號,則說明安裝成功。
常用命令#
git config -l //查看所有配置
git config --system --list //查看系統配置
git config --global --list //查看用戶(全局)配置
配置 Git 用戶名和郵箱#
git config --global user.name "你的用戶名"
git config --global user.email "你的郵箱"
安裝 包管理器#
安裝 npm 為一切的基石,一般來說,你安裝了 node,也相當於你安裝了 npm,通過一下命令來驗證:
npm -v
node -v
修改 npm 源。npm 下載各種模塊,默認是從國外服務器下載,速度較慢,建議配置成淘寶鏡像。打開 CMD 窗口,運行如下命令:
npm config set registry https://registry.npm.taobao.org
安裝 pnpm#
pnpm 是一個快速、節省磁碟空間的包管理器,類似於 npm 和 yarn。安裝 pnpm 可以通過以下命令:
npm install -g pnpm
為什麼選擇 pnpm?因為它的安裝速度快,依賴管理更高效,且相對於 npm,我使用 npm 容易失敗且慢,pnpm 給我的體驗更好。
安裝 Hexo#
- 在 Git BASH 輸入如下命令安裝 Hexo:
pnpm install -g hexo-cli
- 安裝完後輸入
hexo -v
驗證是否安裝成功。
Github 配置#
上述操作是前提,接下來是配置 Github。
註冊 github 就不說了,很基礎的東西,連我個代碼小白都懂就不多說了。
創建倉庫#
- 登錄 GitHub,點擊右上角的
+
號,選擇New repository
。 - 填寫倉庫名稱,建議使用
<username>.github.io
格式(例如:yourusername.github.io
),這樣可以直接作為個人主頁。
這裡我不準備直接使用常規的 hexo deploy
命令來部署到 GitHub Pages,因為當你的文章一多,生成時間就會繁瑣,這裡的建議是使用 Github Actions
來自動部署。
- 首先要創建一個放置源碼的私有倉庫,以下稱之為
hexo-source
, - 然後要生成一個 Github 密鑰:
訪問 Github-> 头像(右上角)-> Settings-> Developer Settings-> Personal access tokens-> generate new token, 創建的 Token 名稱隨意,但必須勾選 repo 項 和 workflows 項。
點擊 鏈接 前往生成
[!NOTE]
!!! token 只會顯示這一次,之後將無法查看,所以務必保證你已經記錄下了 Token。之後如果忘記了就只能重新生成重新配置了。
- 在
hexo-source
倉庫中的設置裡點擊設置 -> action -> General -> 工作流程權限- 勾選
Read and write permissions
,並且勾選Allow <span style="background:#FF0000;"></span>all actions and reusable workflows
。
- 勾選
- 在設置裡 -> Secrets and variables -> Actions -> New repository secret 添加
GITHUBTOKEN
:放置你剛才生成的 Token。
上述是前置條件,接下來要先部署 hexo,你才好繼續下一步。#
初始化 Hexo#
- 在本地新建一個文件夾,例如
hexo-solitude
。 - 這裡我是用的是 vscode 打開該文件夾,然後在終端輸入以下命令來初始化 Hexo:
hexo init (項目名稱)
我一般都不填,直接在文件下下就可以開始,如果你添加了項目名稱,那麼下一步就是:
cd (項目名稱)
- 安裝依賴包:
pnpm install
然後就是選擇你想要的主題,這裡我使用的是Solitude,具體的配置不細講,我只講一部分:
首先就是基本的安裝,這裡還是選擇git clone
沒有別的原因,主要還是會改點源碼,不想改的直接 pnpm 下載即可:
// git安裝
git clone -b dev https://github.com/everfu/hexo-theme-solitude.git themes/solitude
// pnpm 安裝
pnpm i hexo-theme-solitude
然後在_config.yml
裡修改成:
theme: solitude
配置#
下列代碼是我的備忘:
# Hexo Configuration
## Docs: https://hexo.io/docs/configuration.html
## Source: https://github.com/hexojs/hexo/
# Site
title: 喵落閣
subtitle: '克喵的博客'
description: '願你看清一切真相後,依舊熱愛你的家人和朋友。'
keywords: 克喵,kemiao,博客
author: 克喵愛吃滷麵
language: zh-CN
timezone: 'Asia/Shanghai'
# URL
## Set your site url here. For example, if you use GitHub Page, set url as 'https://username.github.io/project'
url: # 填網站地址
permalink: posts/:abbrlink.html
permalink_defaults:
pretty_urls:
trailing_index: true # Set to false to remove trailing 'index.html' from permalinks
trailing_html: true # Set to false to remove trailing '.html' from permalinks
# Directory
source_dir: source
public_dir: public
tag_dir: tags
archive_dir: archives
category_dir: categories
code_dir: downloads/code
i18n_dir: :lang
skip_render:
# Writing
new_post_name: :title.md # File name of new posts
default_layout: post
titlecase: false # Transform title into titlecase
external_link:
enable: true # Open external links in new tab
field: site # Apply to the whole site
exclude: ''
filename_case: 0
render_drafts: false
post_asset_folder: false
relative_link: false
future: true
syntax_highlighter: highlight.js
highlight:
line_number: false
auto_detect: false
tab_replace: ''
wrap: true
hljs: false
prismjs:
preprocess: true
line_number: true
tab_replace: ''
# Home page setting
# path: Root path for your blogs index page. (default = '')
# per_page: Posts displayed per page. (0 = disable pagination)
# order_by: Posts order. (Order by date descending by default)
index_generator:
path: ''
per_page: 10
order_by: -date
# Category & Tag
default_category: uncategorized
category_map:
tag_map:
# Metadata elements
## https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta
meta_generator: true
# Date / Time format
## Hexo uses Moment.js to parse and display date
## You can customize the date format as defined in
## http://momentjs.com/docs/#/displaying/format/
date_format: YYYY-MM-DD
time_format: HH:mm:ss
## updated_option supports 'mtime', 'date', 'empty'
updated_option: 'mtime'
# Pagination
## Set per_page to 0 to disable pagination
per_page: 10
pagination_dir: page
# Include / Exclude file(s)
## include:/exclude: options only apply to the 'source/' folder
include: []
exclude: []
ignore: []
# Extensions
## Plugins: https://hexo.io/plugins/
## Themes: https://hexo.io/themes/
theme: solitude
# Deployment
## Docs: https://hexo.io/docs/one-command-deployment
deploy:
type: git
repo: [email protected]:kemiaofxjun/kemiaofxjun.github.io.git
branch: main
# RSS Feed 配置
feed:
type: atom # 生成 atom.xml
path: atom.xml # 輸出文件名
limit: 20 # 最多顯示文章數 (0=全部)
hub: # PubSubHubbub 中心 (可選)
content: true # 是否包含全文內容 (true=是, false=僅摘要)
content_limit: 140 # 摘要長度(當 content=false 時生效)
content_limit_delim: ' ' # 截斷分隔符
order_by: -date # 按日期倒序排列
autodiscovery: true # 在 HTML 頭部添加自動發現標籤
# 數學公式渲染配置
markdown:
preset: 'default' # 使用的 MD 語法,默認使用的 GFM
render:
html: true # 渲染 html
xhtmlOut: false
langPrefix: 'language-' # 在代碼塊的類名中添加前綴(指定語言時)。
breaks: true
linkify: true # 如果你寫了一個鏈接而不是 [name](link) 方式,會自動識別為鏈接並渲染。
typographer: true # 將替換常見的印刷元素。
quotes: '“”‘’' # 替換文章張的 "" '' 號
enable_rules:
disable_rules:
plugins: # 使用插件
anchors:
level: 2 # 渲染標題的級別(h1,h2,h3)
collisionSuffix: ''
permalink: true
permalinkClass: 'headerlink'
permalinkSide: 'left'
permalinkSymbol: ''
case: 0
separator: '-'
images: # 圖片的一些編譯
lazyload: true # 是否需要渲染 lazyload
prepend_root: false
post_asset: false
inline: false
swpp:
# 是否啟用插件
enable: true
# 是否在發布前自動執行腳本
auto_exec: true
gen_dom: true
# 文章鏈接轉數字或字母:https://github.com/rozbo/hexo-abbrlink
abbrlink:
alg: crc16 #算法: crc16(default) and crc32
rep: hex #進制: dec(default) and hex: dec #輸出進制:十進制和十六進制,默認為10進制。丨dec為十進制,hex
# https://github.com/hexojs/hexo-generator-sitemap
sitemap:
path: sitemap.xml
rel: false
tags: true
categories: true
algolia:
appId: ""
apiKey: ""
adminApiKey: ""
chunkSize: 5000
indexName: "index-name"
fields:
- content:strip:truncate,0,500
- excerpt:strip
- gallery
- permalink
- photos
- slug
- tags
- title
# hexo-safego安全跳轉插件
# see https://blog.liushen.fun/posts/1dfd1f41/
hexo_safego:
# 基本功能設置
general:
enable: true # 啟用插件
enable_base64_encode: true # 使用 Base64 編碼
enable_target_blank: true # 從新窗口打開跳轉頁面
# 安全設置
security:
url_param_name: 'u' # URL 參數名
html_file_name: 'go.html' # 重定向頁面的文件名
ignore_attrs: # 忽略處理的 HTML 結構
- 'data-fancybox'
# 容器與頁面設置
scope:
apply_containers: # 應用的容器選擇器
- '#article-container'
apply_pages: # 應用的頁面路徑
- "/posts/"
- "/devices/"
exclude_pages: # 排除的頁面路徑
# 域名白名單
whitelist:
domain_whitelist: # 允許的白名單域名,通過字符串匹配實現
- "kemeow.top"
- "kemiaosw.top"
- "050815.xyz"
- "314926.xyz"
- "051531.xyz"
# 頁面外觀設置
appearance:
avatar: https://img.314926.xyz/images/2025/08/13/no-background-kemiaofxjun.webp # 跳轉頁面頭像路徑
title: "喵洛閣" # 跳轉頁面標題
subtitle: "安全中心" # 跳轉頁面副標題
darkmode: auto # 是否啟用深色模式
countdowntime: 4 # 跳轉頁面倒計時秒數,如果設置為負數則為不自動跳轉
# 調試設置
debug:
enable: false # 啟用調試模式
# 追番插件
# https://github.com/HCLonely/hexo-bilibili-bangumi
bangumi: # 追番設置
enable: true
source: bili
path:
vmid: 3546643173477234
title: "追番列表"
quote: "生命不息,追番不止!"
show: 1
lazyload: false
loading:
showMyComment: true
pagination: false
extra_options:
top_img: false
lazyload:
enable: false
博客的其他修改基本就是來自教程和一些博主的網站。
插件#
- 基礎依賴
hexo-renderer-pug
pnpm i hexo-renderer-pug
- 字數統計
hexo-wordcount
pnpm i hexo-wordcount
配置裡修改:
# --------------------------- start ---------------------------
# Word count
# 字數統計
# warning: Please install the hexo-wordcount plugin first.
# 警告: 請先安裝 hexo-wordcount 插件。
wordcount: false
# --------------------------- end ---------------------------
- 數學公式 卸載
hexo-render-marked
npm un hexo-renderer-marked
安裝 hexo-renderer-markdown-it
katex
@renbaoshuo/markdown-it-katex
pnpm i hexo-renderer-markdown-it katex @renbaoshuo/markdown-it-katex
配置裡修改
# --------------------------- start ---------------------------
# Katex
# Latex formula support
# Latex 公式支持
katex:
enable: false
# Whether to load on each page
# 是否在每個頁面加載
per_page: false
# Whether to enable copy formula
# 是否啟用複製公式
copytex: false
# --------------------------- end ---------------------------
添加以下內容到 _config.yml
markdown:
preset: 'default'
render:
html: true
xhtmlOut: false
langPrefix: 'language-'
breaks: true
linkify: true
typographer: true
quotes: '“”‘’'
enable_rules:
disable_rules:
plugins:
- '@renbaoshuo/markdown-it-katex'
anchors:
level: 2
collisionSuffix: ''
permalink: false
permalinkClass: 'header-anchor'
permalinkSide: 'left'
permalinkSymbol: '¶'
case: 0
separator: '-'
images:
lazyload: false
prepend_root: false
post_asset: false
inline: false # https://markdown-it.github.io/markdown-it/#MarkdownIt.renderInline
開啟配置項
# --------------------------- start ---------------------------
# Katex
# Latex formula support
# Latex 公式支持
katex:
enable: true
# Whether to load on each page
# 是否在每個頁面加載
per_page: true
# Whether to enable copy formula
# 是否啟用複製公式
copytex: false
# --------------------------- end ---------------------------
- PWA 安裝 hexo-swpp 和 swpp-backends 插件
在博客根目錄執行
pnpm i hexo-swpp
pnpm i swpp-backends
開啟配置
# 大約在773行
# --------------------------- start ---------------------------
# PWA
# Progressive Web App
pwa:
enable: true
manifest: /manifest.json # manifest.json
theme_color: "#006a73" # Theme color
mask_icon: /img/pwa/favicon.png # Mask icon
apple_touch_icon: /img/pwa/favicon.png # Apple touch icon
bookmark_icon: /img/pwa/favicon.png # Bookmark icon
favicon_32_32: /img/pwa/favicon_32.png # 32x32 icon
favicon_16_16: /img/pwa/favicon_16.png # 16x16 icon
# --------------------------- end ---------------------------
在_config.yml
裡添加 swpp 配置
swpp:
# 是否啟用插件
enable: true
# 是否在發布前自動執行腳本
auto_exec: true
gen_dom: true
在 source
目錄中創建 manifest.json
文件
{
"name": "網站名稱",
"short_name": "網站名稱縮寫",
"theme_color": "#006a73",
"background_color": "#006a73",
"display": "fullscreen",
"scope": "/",
"start_url": "/",
"id": "/",
"icons": [
{
"src": "/img/pwa/favicon_16.png",
"sizes": "16x16",
"type": "image/png",
"purpose": "any"
},
{
"src": "/img/pwa/favicon_16.png",
"sizes": "16x16",
"type": "image/png",
"purpose": "maskable"
},
{
"src": "/img/pwa/favicon_32.png",
"sizes": "32x32",
"type": "image/png",
"purpose": "any"
},
{
"src": "/img/pwa/favicon_32.png",
"sizes": "32x32",
"type": "image/png",
"purpose": "maskable"
},
{
"src": "/img/pwa/favicon.png",
"sizes": "180x180",
"type": "image/png",
"purpose": "any"
},
{
"src": "/img/pwa/favicon.png",
"sizes": "180x180",
"type": "image/png",
"purpose": "maskable"
}
],
"splash_pages": null
}
在博客根目錄創建一個 sw-rules.js
文件
module.exports.config = {
/** @type {?ServiceWorkerConfig|boolean} */
serviceWorker: {
escape: 1,
cacheName: 'SolitudeCache',
debug: false,
},
register: {
onsuccess: undefined,
onerror: () =>
console.error(
'Service Worker 註冊失敗!可能是由於您的瀏覽器不支持該功能!'
),
builder: (root, framework, pluginConfig) => {
const { onerror, onsuccess } = pluginConfig.register;
return `
<script>
(() => {
const sw = navigator.serviceWorker;
const error = ${onerror && onerror.toString()};
if (!sw?.register('${new URL(root).pathname}sw.js')
${onsuccess ? `?.then(${onsuccess.toString()})` : ""}
?.catch(error)
) error()
})()
</script>`;
},
},
/** @type {?DomConfig|boolean} */
dom: {
/** @type {?VoidFunction} */
onsuccess: () => {
caches
.match('https://id.v3/')
.then((res) => {
if (res)
res.json().then((json) => {
utils &&
utils.snackbarShow(
`已刷新緩存,更新為${json.escape + '.' + json.global + '.' + json.local
}版本最新內容`,
false,
2500
);
});
else console.info('未找到緩存');
})
.catch((error) => console.error('緩存匹配出錯', error));
},
},
/** @type {?VersionJsonConfig|boolean} */
json: {
/** @type {number} */
maxHtml: 15,
/** @type {number} */
charLimit: 1024,
/** @type {string[]} */
merge: [],
exclude: {
/** @type {RegExp[]} */
localhost: [],
/** @type {RegExp[]} */
other: [],
},
},
/** @type {?ExternalMonitorConfig|boolean} */
external: {
/** @type {number} */
timeout: 5000,
/** 拉取文件時地並發限制 */
concurrencyLimit: 100,
/** @type {({head: string, tail: string}|function(string):string[])[]} */
js: [],
/** @type {RegExp[]} */
stable: [
/^https:\/\/npm\.elemecdn\.com\/[^/@]+\@[^/@]+\/[^/]+\/[^/]+$/,
/^https:\/\/cdn\.cbd\.int\/[^/@]+\@[^/@]+\/[^/]+\/[^/]+$/,
/^https:\/\/cdn\.jsdelivr\.net\/npm\/[^/@]+\@[^/@]+\/[^/]+\/[^/]+$/,
],
replacer: (srcUrl) => {
if (srcUrl.startsWith('https://cdn.jsdelivr.net/npm/')) {
const pathname = new URL(srcUrl).pathname;
return [
srcUrl,
`https://cdn.cbd.int/${pathname}`,
`https://npm.elemecdn.com/${pathname}`,
`https://fastly.jsdelivr.net/npm/${pathname}`,
];
} else {
return srcUrl;
}
},
},
};
module.exports.cacheRules = {
simple: {
clean: true,
search: false,
match: (url, $eject) =>
url.host === $eject.domain && ['/404.html'].includes(url.pathname),
},
cdn: {
clean: true,
match: (url) =>
[
'cdn.cbd.int',
'lf26-cdn-tos.bytecdntp.com',
'lf6-cdn-tos.bytecdntp.com',
'lf3-cdn-tos.bytecdntp.com',
'lf9-cdn-tos.bytecdntp.com',
'cdn.staticfile.org',
'npm.elemecdn.com',
].includes(url.host) &&
url.pathname.match(/\.(js|css|woff2|woff|ttf|cur)$/),
},
};
module.exports.getSpareUrls = (srcUrl) => {
if (srcUrl.startsWith('https://npm.elemecdn.com')) {
return {
timeout: 3000,
list: [
srcUrl,
`https://fastly.jsdelivr.net/${new URL(srcUrl).pathname}`,
],
};
}
};
module.exports.ejectValues = (hexo, rules) => {
return {
domain: {
prefix: 'const',
value: new URL(hexo.config.url).host,
},
};
};
module.exports.skipRequest = (request) => request.url.startsWith("https://i0.hdslb.com") ||
request.url.startsWith('https://meting.qjqq.cn') ||
request.url.startsWith('https://api.i-meto.com');
- hexo-deploy-git 提交到 git 的插件
pnpm i hexo-deploy-git --save
- hexo-generator-feed hexo 的 rss 插件
pnpm i hexo-generator-feed --save
- hexo 的短鏈接:
hexo-abbrlink
pnpm i hexo-abbrlink --save
在_config.yml
裡修改:
permalink: posts/:abbrlink/
# or
permalink: posts/:abbrlink.html
添加:
# abbrlink config
abbrlink:
alg: crc32 # Algorithm used to calc abbrlink. Support crc16(default) and crc32
rep: hex # Representation of abbrlink in URLs. Support dec(default) and hex
drafts: false # Whether to generate abbrlink for drafts. (false in default)
force: false # Enable force mode. In this mode, the plugin will ignore the cache, and calc the abbrlink for every post even it already had an abbrlink. (false in default)
writeback: true # Whether to write changes to front-matters back to the actual markdown files. (true in default)
- 博客的 sitemap :
hexo-generator-sitemap
pnpm i hexo-generator-sitemap --save
在_config.yml
裡添加配置:
sitemap:
path:
- sitemap.xml
- sitemap.txt
template: ./sitemap_template.xml
template_txt: ./sitemap_template.txt
rel: false
tags: true
categories: true
- 使用 algolia 搜索 :
hexo-algoliasearch
- 註冊 algolia:
註冊地址:dashboard.algolia.com/users/sign_up
- 創建應用:
註冊成功後創建應用:dashboard.algolia.com/account/plan/create?from=dashboard
- search -> configure -> index 添加 index_name 即可
在博客執行命令:
pnpm i hexo-algoliasearch --save
_config.yml
裡添加
algolia:
appId: "Z7A3XW4R2I"
apiKey: "12db1ad54372045549ef465881c17e743"
adminApiKey: "40321c7c207e7f73b63a19aa24c4761b"
chunkSize: 5000
indexName: "my-hexo-blog"
fields:
- content:strip:truncate,0,500
- excerpt:strip
- gallery
- permalink
- photos
- slug
- tags
- title
[!NOTE]
!!! 配置完成後記得運行
hexo clean
在hexo g
後執行下列代碼:
hexo algolia
- **hexo-safego** 安全跳轉插件
使用該插件之前,需要先安裝 cheerio
,cheerio
是一個輕量級的庫,用於在服務器端快速、靈活地實現 jQuery 核心功能。在 hexo-safego
插件中,cheerio
被用來解析和操作生成的靜態 HTML 內容,類似於在瀏覽器中使用 jQuery 處理 DOM 元素。這使得插件能夠在生成靜態頁面時,處理和替換外部鏈接,增強博客的安全性,而不需要在客戶端引入 jQuery。Hexo 一般都有這個插件,可以在 node_modules
查看,如果沒有,請先執行:
pnpm i cheerio --save
然後即可安裝該插件:
pnpm i hexo-safego --save
在hexo
根目錄的_config.yml
文件中添加以下配置:
# hexo-safego安全跳轉插件
# see https://blog.liushen.fun/posts/1dfd1f41/
hexo_safego:
# 基本功能設置
general:
enable: true # 啟用插件
enable_base64_encode: true # 使用 Base64 編碼
enable_target_blank: true # 打開新窗口
# 安全設置
security:
url_param_name: 'u' # URL 參數名
html_file_name: 'go.html' # 重定向頁面的文件名
ignore_attrs: # 忽略處理的 HTML 屬性
- 'data-fancybox'
# 容器與頁面設置
scope:
apply_containers: # 應用的容器選擇器
- '#article-container'
apply_pages: # 應用的頁面路徑
- "/posts/"
- "/devices/"
exclude_pages: # 排除的頁面路徑
# 域名白名單
whitelist:
domain_whitelist: # 允許的白名單域名
- "qyliu.top"
- "liushen.fun"
# 頁面外觀設置
appearance:
avatar: /info/avatar.ico # 頭像路徑
title: "清羽飛揚" # 頁面標題
subtitle: "安全中心" # 頁面副標題
darkmode: true # 是否啟用深色模式
countdowntime: -1 # 倒計時秒數
# 調試設置
debug:
enable: false # 啟用調試模式
- hexo 的追番頁面:hexo-bilibili-bangumi
pnpm i hexo-bilibili-bangumi --save
在_config.yml
配置:
bangumi: # 追番設置
enable: true # 是否啟用
source: bili # 數據源
path: bangumis/index.html # 頁面路徑
vmid: # 用戶ID
title: '追番列表' # 頁面標題
quote: '生命不息,追番不止!' # 頁面引言
show: 1 # 初始顯示頁面: 0=想看, 1=在看, 2=看過
lazyload: true # 是否啟用圖片懶加載
metaColor: # meta 信息字體顏色
color: # 簡介字體顏色
webp: true # 是否使用 webp 格式圖片
progress: true # 是否顯示進度條
...
cinema: # 追劇設置
enable: true # 是否啟用
source: bili
...
game: # 遊戲設置,仅支持source: bgmv0
enable: true # 是否啟用
source: bgmv0
...
還在更新中。。。
Github action 配置#
承接段落的繼續吧,未來會在出水一期。
接下來就是創建一個私有倉庫,根據大佬的文章,是為了保護Token,見仁見智。
這個私有倉庫的建立是存儲 Hexo 博客代碼,如果你要使用Qexo
,這也是必不可少的!
創建完成後,需要把博客的源碼 push 到這裡。首先獲取遠程倉庫地址,此處雖然 SSH 和 HTTPS 均可。SSH 在綁定過 ssh key 的設備上無需再輸入密碼,HTTPS 則需要輸入密碼,但是 SSH 偶爾會遇到端口佔用的情況。請自主選擇。
[!TIP]
這裡之所以是私有倉庫,是因為在接下來的配置中會用到
Token
,如果Token
被盜用,別人可以肆意操作你的 github 倉庫內容,為了避免這一風險,才選擇的博客源碼閉源。
配置 Github Action#
- 在
[Blogroot]
新建.github
文件夾,注意開頭是有個.
的。然後在.github
內新建workflows
文件夾,再在workflows
文件夾內新建autodeploy.yml
, 在[Blogroot]/.github/workflows/autodeploy.yml
裡面輸入
# 當有改動推送到 main 分支時,啟動 Action
name: 自動部署
on:
push:
branches:
- main # 自選分支
release:
types:
- published
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: 檢查分支
uses: actions/checkout@v4
with:
ref: main # 自選分支
- name: 安裝 Node
uses: actions/setup-node@v4
with:
node-version: "22.x" # node版本
- name: 安裝 Hexo
run: |
export TZ='Asia/Shanghai'
npm install hexo-cli -g
npm install yamljs --save
- name: 緩存 Hexo
uses: actions/cache@v4
id: cache
with:
path: node_modules
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
- name: 安裝依賴
if: steps.cache.outputs.cache-hit != 'true'
run: |
npm install --save
npm install hexo-algoliasearch --save
npm install hexo-bilibili-bangumi --save
- name: 生成靜態文件
run: |
node ./link.js
hexo clean
hexo generate
hexo bangumi -u
hexo algolia
- name: 部署
run: |
cd ./public
git init -b main
git config --global user.name '${{ secrets.GITHUBUSERNAME }}'
git config --global user.email '${{ secrets.GITHUBEMAIL }}'
git add .
git commit -m "${{ github.event.head_commit.message }} $(date +"%Z %Y-%m-%d %A %H:%M:%S") Updated by GitHub Actions"
git push --force --quiet "https://${{ secrets.GITHUBUSERNAME }}:${{ secrets.GITHUBTOKEN }}@github.com/${{ secrets.GITHUBUSERNAME }}/${{ secrets.GITHUBUSERNAME }}.github.io.git" main
-
首先把 Token 直接放在倉庫的文件裡還是不太好。
-
像我這種在本地搞的,推不到倉庫裡,因為這裡的 token 不能直接上傳,我嘗試過把
token:
改成token: ${{ servets.GH_token }}
,但是依舊有各種問題,相反使用了店長的代碼後,就大差不差,詢問 AI 後就得到目前的代碼,也就可以正式上傳了。(無拉踩的意思) -
之後需要自己到倉庫的 Settings->Secrets->actions 下添加環境變量,變量名參考腳本中出現的,依次添加。
重新設置遠程倉庫和分支#
🍼第一次使用git管理博客源碼
1. 刪除或者先把`[Blogroot]/themes/solitude/.git`移動到非博客文件夾目錄下,原因是主題文件夾下的`.git`文件夾的存在會導致其被識別成子項目,從而無法被上傳到源碼倉庫。- 在博客根目錄
[Blogroot]
路徑下運行指令:
git init #初始化
git remote add origin [email protected]:[GithubUsername]/[SourceRepo].git #[SourceRepo]為存放源碼的github私有倉庫
git checkout -b master # 切換到master分支,
#2020年10月後github新建倉庫默認分支改為main,注意更改
# 如果不是,後面的所有設置的分支記得保持一致
- 添加屏蔽項
.DS_Store
Thumbs.db
db.json
*.log
node_modules/
public/
.deploy*/
.deploy_git*/
.idea
themes/solitude/.git
如果不是solitude
主題,記得替換最後一行內容為你自己當前使用的主題。
4. 之後再運行 git 提交指令,將博客源碼提交到 github 上。
git add .
git commit -m "github action update"
git push origin master
#2020年10月後github新建倉庫默認分支改為main,注意更改
- 此時你的主題文件夾若已經被正常上傳,並且你也添加了主題文件夾下的.git 文件夾的屏蔽項。那你可以考慮把第二步移走或刪除的
.git
放回來,用作以後升級。(不禁懷疑真的有人會去用這個方式來升級嗎)
🍾曾經做過git管理源碼的操作
1. 添加屏蔽項因為能夠使用指令進行安裝的內容不包括在需要提交的源碼內,所有我們需要將這些內容添加到屏蔽項,表示不上傳到 github 上。這樣可以顯著減少需要提交的文件量和加快提交速度。
打開[Blogroot]/.gitignore
, 輸入以下內容:
.DS_Store
Thumbs.db
db.json
*.log
node_modules/
public/
.deploy*/
.deploy_git*/
.idea
themes/solitude/.git
如果不是solitude
主題,記得替換最後一行內容為你自己當前使用的主題。
- 提交源碼到私有倉庫
[SourceRepo]
在博客根目錄[Blogroot]
下啟動終端,使用 git 指令重設倉庫地址。這樣在新建倉庫,我們仍舊可以保留珍貴的 commit history,便於版本回滾。
git remote rm origin # 刪除原有倉庫鏈接
git remote add origin [email protected]:[GithubUsername]/[SourceRepo].git #[SourceRepo]為新的存放源碼的github私有倉庫
git checkout -b master # 切換到master分支,
#2020年10月後github新建倉庫默認分支改為main,注意更改
# 如果不是,後面的所有設置的分支記得保持一致
git add .
git commit -m "github action update"
git push origin master
#2020年10月後github新建倉庫默認分支改為main,注意更改
- 可能遇到的 bug
因為 solitude 主題文件夾下的.git 文件夾的存在,那麼主題文件夾會被識別子項目。從而無法被上傳到源碼倉庫。若是遇到添加屏蔽項,但是還是無法正常上傳主題文件夾的情況。請先將本地源碼中的 themes 文件夾移動到別的目錄下。然後 commit 一次。接著將 themes 文件夾移動回來,再 commit 一次。
Important
要是還不行,那就刪了 solitude 主題文件夾下的.git 文件夾,然後再重複上述的 commit 操作。
挖坑#
大致寫到這,未來或許會有下一章挖坑?但是目前通用的就到這,然後後續會寫 Qexo 的簡單使用方法、solitude 的一些配置更改和我踩坑經歷吧。