Astro 是一個現代化的靜態網站生成器,以其出色的性能和開發體驗受到廣泛歡迎。本文將介紹如何在蘋果電腦 Apple macOS 上從零開始搭建 Astro 開發環境並部署到 Cloudflare Pages。
🚀 環境準備
1. 安裝必要工具
# 安裝 Homebrew(如果尚未安裝)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
# 安裝 Node.js(Astro 需要 Node.js 18+)
brew install node
# 驗證安裝
node --version
npm --version2. 創建 Astro 項目
# 使用官方腳本創建新項目
npm create astro@latest my-astro-site
# 進入項目目錄
cd my-astro-site
# 安裝依賴
npm install🛠️ 開發階段
啟動開發服務器
npm run dev訪問 http://localhost:4321 查看你的網站,支持熱重載,修改代碼即時可見。
項目結構概覽
my-astro-site/
├── src/
│ ├── pages/ # 頁面組件
│ ├── layouts/ # 佈局組件
│ └── components/ # 可復用組件
├── public/ # 靜態資源
└── astro.config.mjs # 配置文件添加頁面
在 src/pages/ 創建 .astro 或 .md 文件:
---
// src/pages/about.astro
---
<html>
<head>
<title>關於我們</title>
</head>
<body>
<h1>歡迎來到 Astro!</h1>
<p>這是一個靜態生成的頁面。</p>
<p>Mountos Code Lab</p>
</body>
</html>📦 構建優化
生產環境構建
npm run build構建後的文件將生成在 dist/ 文件夾,適合部署到任何靜態託管服務。
預覽生產版本
npm run preview☁️ 部署到 Cloudflare Pages
1. 準備部署配置
在項目根目錄創建 wrangler.toml:
name = "my-astro-site"
compatibility_date = "2024-01-01"
[pages]
build_command = "npm run build"
build_output_dir = "dist"2. 推送到 GitHub
# 初始化 Git
git init
git add .
git commit -m "Initial Astro project"
# 連接到 GitHub 倉庫
git remote add origin https://github.com/你的用戶名/你的倉庫名.git
git push -u origin main3. 配置 Cloudflare Pages
- 登錄 Cloudflare Dashboard
- 進入 “Workers & Pages”
- 點擊 “Create application” → “Pages”
- 連接你的 GitHub 倉庫
- 構建設置:
- Build command:
npm run build - Build output directory:
dist
4. 自動部署
此後每次推送代碼到 GitHub,Cloudflare Pages 都會自動構建和部署:
git add .
git commit -m "更新網站內容"
git push origin main💡 實用技巧
添加自定義域名
在 Cloudflare Pages 項目的 “Custom domains” 中添加你的域名。
環境變量配置
在 Cloudflare Pages 的 “Environment variables” 中設置生產環境變量。
性能優化
# 分析包大小
npm run build && npx bundle-analyzerdist/_astro/🎯 總結
整個流程非常簡單:
- 本地開發:
npm run dev - 代碼管理:推送到 GitHub
- 自動部署:Cloudflare Pages 處理構建和發布
Astro 加上 Cloudflare Pages 的組合,為開發者提供了快速、免費且高性能的網站託管方案。現在就開始構建你的第一個 Astro 網站吧!
提示:記得定期更新 Astro 版本以獲得最新功能和安全更新:npm update astro


發佈留言