Please enable Javascript to view the contents

Netlify 部署靜態網站

 ·  ☕ 2 min read

事前準備

Netlify 簡介

Netlify 是一個熱門的靜態網站 Host 服務,其免費額度非常適合一般使用者

可以自定義 subdomain 也可以使用自己的網域名,同時也提供了免費的 SSL

而且只要將網站上傳到 GitHub Repository,Netlify 就會自動部署,非常方便

準備靜態網站

這裡以 Hugo 建立的網站為例 (如何使用 Hugo 建立一個靜態網站)
在部署之前,在網站根目錄新增一個 netlify.toml
新增內容如下,注意 HUGO_VERSION

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
[build]
publish = "public"
command = "hugo --gc --minify"

[context.production.environment]
HUGO_VERSION = "0.71.0"
HUGO_ENV = "production"
HUGO_ENABLEGITINFO = "true"

[context.split1]
command = "hugo --gc --minify --enableGitInfo"

[context.split1.environment]
HUGO_VERSION = "0.71.0"
HUGO_ENV = "production"

[context.deploy-preview]
command = "hugo --gc --minify --buildFuture -b $DEPLOY_PRIME_URL"

[context.deploy-preview.environment]
HUGO_VERSION = "0.71.0"

[context.branch-deploy]
command = "hugo --gc --minify -b $DEPLOY_PRIME_URL"

[context.branch-deploy.environment]
HUGO_VERSION = "0.71.0"

[context.next.environment]
HUGO_ENABLEGITINFO = "true"

提交所有改動

1
2
3
git init	# 建立本地 Git 儲存庫,如果之前已建立就不用再執行
git add -A	# add 所有檔案
git commit -m "Initial commit"	# 提交到本地

GitHub 建立一個儲存庫 (可以是私人的)


create github repository

建立完成後,會得到這個儲存庫的連結,複製起來

https://github.com/你的 GitHub 名稱/儲存庫名稱.git

再來將本地的儲存庫推送到 GitHub 上

1
2
git remote add origin https://github.com/你的 GitHub 名稱/儲存庫名稱.git	# 增加遠端儲存庫,名為 origin
git push -u origin master	# 推送本地 master 到遠端 origin

若推送成功就可以看到自己的 GitHub 儲存庫上有東西了

部署到 Netlify

Netlify 官網,登入後點選 New site from Git


new site from git

點選 GitHub


new site from git step 1

授權 Netlify 存取 GitHub


authorize netlify

選擇儲存庫


select repository

點進去


new site from git step 2

可以看到已經讀取到 netlify.toml 的設定了
預設部署是 master 分支,確認後按下 Deploy site


deploy setting

如果沒問題,應該就會 Deploy 成功吧
可惜我失敗了


deploy failed

看了一下 log 發現在 Build 時會去找一個資料夾,但是裡面沒東西
Git 提交會忽略空資料夾,因此我在裡面隨便放個檔案再重新提交一次
重新 Build 之後,但還是失敗
這次是新的錯誤

Error: Error building site: failed to render pages: JSON parse error: unexpected comma character on line 9 and column 20
    9:     "description": ,

沒有找出原因,因此決定先移除 --minify
就成功部署了,那串網址就是網站了
接著改成自己的網域,點選 Deploy settings


deploy success

到 Domain management 頁面點選 Add custom domain


add custom domain

輸入網域名


enter custom domain

接著點選 Check DNS configuration


check dns configuration

將後面那串複製起來,到自己的域名供應商增加 CNAME
等待其生效


add cname

生效後回到 Netlify 下方驗證,成功後就會獲得 Let’s Encrypt 頒發的憑證
也可以使用自己的憑證


verify dns configuration

沒問題的話就成功囉
之後如果有更新,推送至 GitHub 後 Netlify 就會自動部署啦,真棒

Done

分享
您的鼓勵是我最大的動力

JIHONGO
作者
JIHONGO
A Person