Vercel 部署 React 完整教學|2025 從零開始上線指南
React 專案做好了,接下來呢?
部署到 Vercel,讓全世界都能看到你的作品。
免費、快速、簡單。
這篇文章教你如何把 React 應用部署到 Vercel。
為什麼選擇 Vercel 部署 React?
Vercel 對 React 的優勢
| 優勢 | 說明 |
|---|---|
| 零配置部署 | 自動偵測 React 專案 |
| 全球 CDN | 靜態資源快速載入 |
| 自動 HTTPS | 免費 SSL 憑證 |
| Preview 部署 | 每個 PR 都有預覽網址 |
| 無限專案 | 免費方案不限專案數 |
支援的 React 框架
- Create React App (CRA)
- Vite + React
- Next.js(最佳整合)
- Remix
- Gatsby
準備工作
確認專案結構
Create React App:
my-react-app/
├── public/
│ └── index.html
├── src/
│ ├── App.js
│ └── index.js
├── package.json
└── README.md
Vite + React:
my-vite-app/
├── public/
├── src/
│ ├── App.jsx
│ └── main.jsx
├── index.html
├── package.json
└── vite.config.js
確認 package.json
{
"name": "my-react-app",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
}
}
確保有 build 指令。
本機測試
# 執行 build
npm run build
# 測試 build 結果
npm run preview
# 或
npx serve dist
方法一:從 GitHub 部署
步驟一:推送到 GitHub
# 初始化 Git(如果還沒有)
git init
git add .
git commit -m "Initial commit"
# 建立 GitHub Repository 並推送
gh repo create my-react-app --public --source=. --push
# 或手動在 GitHub 建立後
git remote add origin https://github.com/username/my-react-app.git
git push -u origin main
步驟二:連接 Vercel
- 前往 vercel.com
- 點擊 Add New → Project
- 選擇你的 GitHub Repository
- 點擊 Import
步驟三:設定專案
Vercel 會自動偵測 React 專案,通常不需要改設定:
| 設定項目 | Create React App | Vite |
|---|---|---|
| Framework | Create React App | Vite |
| Build Command | npm run build |
npm run build |
| Output Directory | build |
dist |
步驟四:部署
點擊 Deploy,等待 1-2 分鐘。
完成後你會得到網址:https://your-app.vercel.app
方法二:Vercel CLI 部署
安裝 Vercel CLI
npm install -g vercel
登入
vercel login
部署
# 在專案目錄執行
vercel
# 會問幾個問題
# ? Set up and deploy? Yes
# ? Which scope? Your Account
# ? Link to existing project? No
# ? What's your project's name? my-react-app
# ? In which directory is your code located? ./
# ? Want to modify these settings? No
部署到 Production
vercel --prod
環境變數設定
React 環境變數規則
Create React App:
- 必須以
REACT_APP_開頭 - 在 build 時注入
# .env
REACT_APP_API_URL=https://api.example.com
REACT_APP_GA_ID=G-XXXXXX
// 使用方式
const apiUrl = process.env.REACT_APP_API_URL;
Vite:
- 必須以
VITE_開頭 - 在 build 時注入
# .env
VITE_API_URL=https://api.example.com
VITE_GA_ID=G-XXXXXX
// 使用方式
const apiUrl = import.meta.env.VITE_API_URL;
在 Vercel 設定環境變數
- 進入專案 Settings
- 點擊 Environment Variables
- 新增變數(不要忘記前綴)
Name: VITE_API_URL
Value: https://api.example.com
Environment: Production, Preview, Development
不同環境不同值
| 變數 | Production | Preview |
|---|---|---|
| VITE_API_URL | https://api.example.com | https://staging-api.example.com |
| VITE_DEBUG | false | true |
路由設定
React Router 設定
React 是 SPA(單頁應用),需要設定重寫規則。
vercel.json:
{
"rewrites": [
{
"source": "/(.*)",
"destination": "/index.html"
}
]
}
這樣直接訪問 /about 不會得到 404。
檢查路由
// App.jsx
import { BrowserRouter, Routes, Route } from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
);
}
效能優化
啟用 Code Splitting
// 使用 React.lazy 分割程式碼
import { lazy, Suspense } from 'react';
const About = lazy(() => import('./pages/About'));
const Contact = lazy(() => import('./pages/Contact'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<Routes>
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</Suspense>
);
}
圖片優化
使用 WebP 格式:
<picture>
<source srcSet="/image.webp" type="image/webp" />
<img src="/image.jpg" alt="描述" />
</picture>
延遲載入圖片:
<img src="/image.jpg" loading="lazy" alt="描述" />
設定快取標頭
// vercel.json
{
"headers": [
{
"source": "/assets/(.*)",
"headers": [
{
"key": "Cache-Control",
"value": "public, max-age=31536000, immutable"
}
]
}
]
}
壓縮 Bundle
Vite 自動壓縮,但可以進一步優化:
// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
build: {
rollupOptions: {
output: {
manualChunks: {
vendor: ['react', 'react-dom'],
router: ['react-router-dom'],
},
},
},
},
});
API 整合
使用環境變數
// api.js
const API_URL = import.meta.env.VITE_API_URL;
export async function fetchData() {
const res = await fetch(`${API_URL}/data`);
return res.json();
}
處理 CORS
如果 API 在不同網域,可能需要設定 CORS。
方法一:API 端設定 CORS
方法二:使用 Vercel Rewrites 代理
// vercel.json
{
"rewrites": [
{
"source": "/api/:path*",
"destination": "https://api.example.com/:path*"
}
]
}
然後在 React 中:
// 直接呼叫 /api/data,會被代理到 https://api.example.com/data
const res = await fetch('/api/data');
常見問題排解
問題一:Build 失敗
錯誤訊息:
npm ERR! Missing script: "build"
解決方法:
確認 package.json 有 build 指令:
{
"scripts": {
"build": "vite build"
}
}
問題二:頁面空白
可能原因:
- 路由設定問題
homepage設定錯誤
解決方法:
如果用 Create React App,檢查 package.json:
{
"homepage": "."
}
或移除 homepage 設定。
問題三:環境變數讀不到
檢查項目:
- 變數名稱是否有正確前綴(
REACT_APP_或VITE_) - 是否重新部署了(環境變數更改後需要重新 build)
- 是否在 Vercel Dashboard 正確設定
偵錯:
console.log('API URL:', import.meta.env.VITE_API_URL);
console.log('All env:', import.meta.env);
問題四:路由 404
原因:
SPA 需要所有路由都返回 index.html。
解決方法:
新增 vercel.json:
{
"rewrites": [
{ "source": "/(.*)", "destination": "/index.html" }
]
}
問題五:部署很慢
優化方法:
- 減少依賴
- 使用
npm ci而不是npm install - 設定
.vercelignore
# .vercelignore
node_modules
.git
*.md
tests/
自動化部署
GitHub Actions + Vercel
# .github/workflows/deploy.yml
name: Deploy to Vercel
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test
- name: Deploy to Vercel
uses: amondnet/vercel-action@v25
with:
vercel-token: ${{ secrets.VERCEL_TOKEN }}
vercel-org-id: ${{ secrets.VERCEL_ORG_ID }}
vercel-project-id: ${{ secrets.VERCEL_PROJECT_ID }}
vercel-args: '--prod'
取得 Vercel Token
- Vercel Dashboard → Settings → Tokens
- 建立新 Token
- 在 GitHub Repository Settings → Secrets 新增
部署檢查清單
部署前
- [ ]
npm run build本機測試成功 - [ ] 環境變數已設定
- [ ] 路由設定正確(vercel.json)
- [ ] 敏感資訊沒有寫在程式碼中
- [ ]
.gitignore正確設定
部署後
- [ ] 首頁正常顯示
- [ ] 所有路由可訪問
- [ ] API 連線正常
- [ ] 環境變數正確
- [ ] HTTPS 正常
常見問題 FAQ
Q1:Vercel 部署 React 免費嗎?
是的,Hobby 方案免費,包含:
- 每月 100 GB 頻寬
- 6,000 Build 分鐘
- 無限專案
Q2:Create React App 和 Vite 哪個好?
2025 年建議使用 Vite:
- 更快的開發伺服器
- 更快的 build
- 更好的 DX
Q3:可以部署到自訂網域嗎?
可以,在 Settings → Domains 設定。
Q4:如何回滾到之前的版本?
- Vercel Dashboard → Deployments
- 找到要回滾的版本
- 點擊選單 → Promote to Production
Q5:React 專案適合用 Vercel 嗎?
非常適合:
- 靜態 SPA 部署簡單
- 全球 CDN 加速
- 如果需要 SSR,建議改用 Next.js
Vercel 部署失敗?
Build Error、環境變數、自訂網域,我們幫你快速排除問題。