2023 第4週 實作筆記:使用 Makefile 搭配 vite 處理 GitHub Pages 部署

總結

準備將 vite React App 部署到 GitHub Pages 時發現腳本略長,塞到 package.jsonscripts 欄位中不易閱讀,故選擇試用 make 來管理腳本。

版本與環境

os: macOS Ventura Version 13.0

筆記

關於 make

首次出現在 1976 年的軟體,會讀取特定檔案 Makefile 中的內容來建置程式。

Wikipedia: In software development, Make is a build automation tool that automatically builds executable programs and libraries from source code by reading files called Makefile which specify how to derive the target program. Though integrated development environments and language-specific compiler features can also be used to manage a build process, Make remains widely used, especially in Unix and Unix-like operating systems.

在前端專案的其中一種應用:可以讓 package.json 中的 scripts 部分變得簡潔。參考以下內容:

{
  "scripts": {
    "dev": "make dev",
    "build": "make build",
    "preview": "make preview",
    "deploy": "make deploy"
  }
}

在終端輸入 npm run dev 或是 make dev 都能觸發 dev 的效果。

原本就簡短的指令(比如 vite template ts-react 中的 devbuild 分別只是 vitetsc && vite build 這種短組合)換成 make 可能沒有什麼顯著優化。但以本次的使用情境(將 vite React App 部署為 GitHub Pages)來說,使用 Makefile 來管理腳本的話,就能夠分行撰寫指令,也能從 .env 引入變數,提升程式碼的可讀性與維護性。

程式碼與相關說明可參考本文下一段。

搭配 vite 部署 GitHub Pages

Makefile 放在專案根目錄,部署相關的腳本參考 vite: Deploying a Static Site 進行改編:

include .env

# open vite dev server
.PHONY: dev
dev:
	npx vite

# build vite app with production setting
.PHONY: build
build:
	npx tsc && npx vite build

# preview build result locally
.PHONY: preview
preview:
	npx vite preview

# remove build folder and its content
.PHONY: clean
clean:
	rm -rf $(VITE_BUILD_OUTDIR)

# deploy build result to gitHub repo as branch "gh-pages"
.PHONY: deploy
deploy: build
	cd $(VITE_BUILD_OUTDIR) && \
	git init && \
	git remote -v | grep -w origin || git remote add origin git@github.com:<GitHub Account>/<GitHub Repository Name>.git && \
	git branch -m gh-pages && \
	git add -A && \
	git commit -m "[feat] deploy as gh-pages `date +'%Y-%m-%d %H:%M:%S'`" && \
	git push -u origin gh-pages -f

Makefile 相關解說:

gnu.org: A phony target is one that is not really the name of a file; rather it is just a name for a recipe to be executed when you make an explicit request. There are two reasons to use a phony target: to avoid a conflict with a file of the same name, and to improve performance.

Makefile Cheat Sheet: Dependencies can either be other targets or file names; if a target depends on another target, it guarantees that target will be run prior, and if a target depends on a file, it will check to see if that file has changed to avoid executing redundantly. Finally, commands can be anything you could run on your command line.

其他補充:

參考文件