azure-static-web-apps
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseOverview
概述
Azure Static Web Apps (SWA) hosts static frontends with optional serverless API backends. The SWA CLI () provides local development emulation and deployment capabilities.
swaKey features:
- Local emulator with API proxy and auth simulation
- Framework auto-detection and configuration
- Direct deployment to Azure
- Database connections support
Config files:
- - CLI settings, created by
swa-cli.config.json(never create manually)swa init - - Runtime config (routes, auth, headers, API runtime) - can be created manually
staticwebapp.config.json
Azure Static Web Apps (SWA) 托管静态前端,并可搭配可选的无服务器API后端。SWA CLI()提供本地开发模拟和部署功能。
swa主要特性:
- 包含API代理和身份验证模拟的本地模拟器
- 框架自动检测与配置
- 直接部署到Azure
- 支持数据库连接
配置文件:
- - CLI设置,通过
swa-cli.config.json创建(切勿手动创建)swa init - - 运行时配置(路由、身份验证、请求头、API运行时)- 可手动创建
staticwebapp.config.json
General Instructions
通用说明
Installation
安装
bash
npm install -D @azure/static-web-apps-cliVerify:
npx swa --versionbash
npm install -D @azure/static-web-apps-cli验证:
npx swa --versionQuick Start Workflow
快速开始流程
IMPORTANT: Always use to create configuration files. Never manually create .
swa initswa-cli.config.json- - Required first step - auto-detects framework and creates
swa initswa-cli.config.json - - Run local emulator at
swa starthttp://localhost:4280 - - Authenticate with Azure
swa login - - Deploy to Azure
swa deploy
重要提示:始终使用创建配置文件。切勿手动创建。
swa initswa-cli.config.json- - 必须执行的第一步 - 自动检测框架并创建
swa initswa-cli.config.json - - 在
swa start启动本地模拟器http://localhost:4280 - - 登录Azure进行身份验证
swa login - - 部署到Azure
swa deploy
Configuration Files
配置文件
swa-cli.config.json - Created by , do not create manually:
swa init- Run for interactive setup with framework detection
swa init - Run to accept auto-detected defaults
swa init --yes - Edit the generated file only to customize settings after initialization
Example of generated config (for reference only):
json
{
"$schema": "https://aka.ms/azure/static-web-apps-cli/schema",
"configurations": {
"app": {
"appLocation": ".",
"apiLocation": "api",
"outputLocation": "dist",
"appBuildCommand": "npm run build",
"run": "npm run dev",
"appDevserverUrl": "http://localhost:3000"
}
}
}staticwebapp.config.json (in app source or output folder) - This file CAN be created manually for runtime configuration:
json
{
"navigationFallback": {
"rewrite": "/index.html",
"exclude": ["/images/*", "/css/*"]
},
"routes": [
{ "route": "/api/*", "allowedRoles": ["authenticated"] }
],
"platform": {
"apiRuntime": "node:20"
}
}swa-cli.config.json - 通过创建,请勿手动创建:
swa init- 运行进行交互式设置,自动检测框架
swa init - 运行接受自动检测的默认设置
swa init --yes - 仅在初始化后可编辑生成的文件来自定义设置
生成的配置示例(仅供参考):
json
{
"$schema": "https://aka.ms/azure/static-web-apps-cli/schema",
"configurations": {
"app": {
"appLocation": ".",
"apiLocation": "api",
"outputLocation": "dist",
"appBuildCommand": "npm run build",
"run": "npm run dev",
"appDevserverUrl": "http://localhost:3000"
}
}
}staticwebapp.config.json(位于应用源码或输出文件夹中)- 此文件可手动创建用于运行时配置:
json
{
"navigationFallback": {
"rewrite": "/index.html",
"exclude": ["/images/*", "/css/*"]
},
"routes": [
{ "route": "/api/*", "allowedRoles": ["authenticated"] }
],
"platform": {
"apiRuntime": "node:20"
}
}Command-line Reference
命令行参考
swa login
swa login
Authenticate with Azure for deployment.
bash
swa login # Interactive login
swa login --subscription-id <id> # Specific subscription
swa login --clear-credentials # Clear cached credentialsFlags: | | | | |
--subscription-id, -S--resource-group, -R--tenant-id, -T--client-id, -C--client-secret, -CS--app-name, -n登录Azure以进行部署。
bash
swa login # 交互式登录
swa login --subscription-id <id> # 指定订阅
swa login --clear-credentials # 清除缓存的凭据参数: | | | | |
--subscription-id, -S--resource-group, -R--tenant-id, -T--client-id, -C--client-secret, -CS--app-name, -nswa init
swa init
Configure a new SWA project based on an existing frontend and (optional) API. Detects frameworks automatically.
bash
swa init # Interactive setup
swa init --yes # Accept defaults基于现有前端和(可选)API配置新的SWA项目。自动检测框架。
bash
swa init # 交互式设置
swa init --yes # 接受默认设置swa build
swa build
Build frontend and/or API.
bash
swa build # Build using config
swa build --auto # Auto-detect and build
swa build myApp # Build specific configurationFlags: | | | |
--app-location, -a--api-location, -i--output-location, -O--app-build-command, -A--api-build-command, -I构建前端和/或API。
bash
swa build # 使用配置文件构建
swa build --auto # 自动检测并构建
swa build myApp # 构建特定配置参数: | | | |
--app-location, -a--api-location, -i--output-location, -O--app-build-command, -A--api-build-command, -Iswa start
swa start
Start local development emulator.
bash
swa start # Serve from outputLocation
swa start ./dist # Serve specific folder
swa start http://localhost:3000 # Proxy to dev server
swa start ./dist --api-location ./api # With API folder
swa start http://localhost:3000 --run "npm start" # Auto-start dev serverCommon framework ports:
| Framework | Port |
|---|---|
| React/Vue/Next.js | 3000 |
| Angular | 4200 |
| Vite | 5173 |
Key flags:
- - Emulator port (default: 4280)
--port, -p - - API folder path
--api-location, -i - - API port (default: 7071)
--api-port, -j - - Command to start dev server
--run, -r - - Open browser automatically
--open, -o - - Enable HTTPS
--ssl, -s
启动本地开发模拟器。
bash
swa start # 从outputLocation提供服务
swa start ./dist # 为特定文件夹提供服务
swa start http://localhost:3000 # 代理到开发服务器
swa start ./dist --api-location ./api # 搭配API文件夹
swa start http://localhost:3000 --run "npm start" # 自动启动开发服务器常见框架端口:
| 框架 | 端口 |
|---|---|
| React/Vue/Next.js | 3000 |
| Angular | 4200 |
| Vite | 5173 |
主要参数:
- - 模拟器端口(默认:4280)
--port, -p - - API文件夹路径
--api-location, -i - - API端口(默认:7071)
--api-port, -j - - 启动开发服务器的命令
--run, -r - - 自动打开浏览器
--open, -o - - 启用HTTPS
--ssl, -s
swa deploy
swa deploy
Deploy to Azure Static Web Apps.
bash
swa deploy # Deploy using config
swa deploy ./dist # Deploy specific folder
swa deploy --env production # Deploy to production
swa deploy --deployment-token <TOKEN> # Use deployment token
swa deploy --dry-run # Preview without deployingGet deployment token:
- Azure Portal: Static Web App → Overview → Manage deployment token
- CLI:
swa deploy --print-token - Environment variable:
SWA_CLI_DEPLOYMENT_TOKEN
Key flags:
- - Target environment (
--envorpreview)production - - Deployment token
--deployment-token, -d - - Azure SWA resource name
--app-name, -n
部署到Azure Static Web Apps。
bash
swa deploy # 使用配置文件部署
swa deploy ./dist # 部署特定文件夹
swa deploy --env production # 部署到生产环境
swa deploy --deployment-token <TOKEN> # 使用部署令牌
swa deploy --dry-run # 预览部署(不实际部署)获取部署令牌:
- Azure门户:静态Web应用 → 概述 → 管理部署令牌
- CLI:
swa deploy --print-token - 环境变量:
SWA_CLI_DEPLOYMENT_TOKEN
主要参数:
- - 目标环境(
--env或preview)production - - 部署令牌
--deployment-token, -d - - Azure SWA资源名称
--app-name, -n
swa db
swa db
Initialize database connections.
bash
swa db init --database-type mssql
swa db init --database-type postgresql
swa db init --database-type cosmosdb_nosql初始化数据库连接。
bash
swa db init --database-type mssql
swa db init --database-type postgresql
swa db init --database-type cosmosdb_nosqlScenarios
场景示例
Create SWA from Existing Frontend and Backend
从现有前端和后端创建SWA
Always run before or . Do not manually create .
swa initswa startswa deployswa-cli.config.jsonbash
undefined在运行或之前,务必先运行。切勿手动创建。
swa startswa deployswa initswa-cli.config.jsonbash
undefined1. Install CLI
1. 安装CLI
npm install -D @azure/static-web-apps-cli
npm install -D @azure/static-web-apps-cli
2. Initialize - REQUIRED: creates swa-cli.config.json with auto-detected settings
2. 初始化 - 必须执行:创建包含自动检测设置的swa-cli.config.json
npx swa init # Interactive mode
npx swa init # 交互式模式
OR
或
npx swa init --yes # Accept auto-detected defaults
npx swa init --yes # 接受自动检测的默认设置
3. Build application (if needed)
3. 构建应用(如有需要)
npm run build
npm run build
4. Test locally (uses settings from swa-cli.config.json)
4. 本地测试(使用swa-cli.config.json中的设置)
npx swa start
npx swa start
5. Deploy
5. 部署
npx swa login
npx swa deploy --env production
undefinednpx swa login
npx swa deploy --env production
undefinedAdd Azure Functions Backend
添加Azure Functions后端
- Create API folder:
bash
mkdir api && cd api
func init --worker-runtime node --model V4
func new --name message --template "HTTP trigger"- Example function ():
api/src/functions/message.js
javascript
const { app } = require('@azure/functions');
app.http('message', {
methods: ['GET', 'POST'],
authLevel: 'anonymous',
handler: async (request) => {
const name = request.query.get('name') || 'World';
return { jsonBody: { message: `Hello, ${name}!` } };
}
});- Set API runtime in :
staticwebapp.config.json
json
{
"platform": { "apiRuntime": "node:20" }
}- Update CLI config in :
swa-cli.config.json
json
{
"configurations": {
"app": { "apiLocation": "api" }
}
}- Test locally:
bash
npx swa start ./dist --api-location ./api- 创建API文件夹:
bash
mkdir api && cd api
func init --worker-runtime node --model V4
func new --name message --template "HTTP trigger"- 示例函数():
api/src/functions/message.js
javascript
const { app } = require('@azure/functions');
app.http('message', {
methods: ['GET', 'POST'],
authLevel: 'anonymous',
handler: async (request) => {
const name = request.query.get('name') || 'World';
return { jsonBody: { message: `Hello, ${name}!` } };
}
});- 在中设置API运行时:
staticwebapp.config.json
json
{
"platform": { "apiRuntime": "node:20" }
}- 在中更新CLI配置:
swa-cli.config.json
json
{
"configurations": {
"app": { "apiLocation": "api" }
}
}- 本地测试:
bash
npx swa start ./dist --api-location ./api
**Supported API runtimes:** `node:18`, `node:20`, `node:22`, `dotnet:8.0`, `dotnet-isolated:8.0`, `python:3.10`, `python:3.11`
**支持的API运行时:** `node:18`, `node:20`, `node:22`, `dotnet:8.0`, `dotnet-isolated:8.0`, `python:3.10`, `python:3.11`Set Up GitHub Actions Deployment
配置GitHub Actions部署
- Create SWA resource in Azure Portal or via Azure CLI
- Link GitHub repository - workflow auto-generated, or create manually:
.github/workflows/azure-static-web-apps.ymlyaml
name: Azure Static Web Apps CI/CD
on:
push:
branches: [main]
pull_request:
types: [opened, synchronize, reopened, closed]
branches: [main]
jobs:
build_and_deploy:
if: github.event_name == 'push' || (github.event_name == 'pull_request' && github.event.action != 'closed')
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Build And Deploy
uses: Azure/static-web-apps-deploy@v1
with:
azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN }}
repo_token: ${{ secrets.GITHUB_TOKEN }}
action: upload
app_location: /
api_location: api
output_location: dist
close_pr:
if: github.event_name == 'pull_request' && github.event.action == 'closed'
runs-on: ubuntu-latest
steps:
- uses: Azure/static-web-apps-deploy@v1
with:
azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN }}
action: close- Add secret: Copy deployment token to repository secret
AZURE_STATIC_WEB_APPS_API_TOKEN
Workflow settings:
- - Frontend source path
app_location - - API source path
api_location - - Built output folder
output_location - - Skip if pre-built
skip_app_build: true - - Custom build command
app_build_command
- 在Azure门户或通过Azure CLI创建SWA资源
- 关联GitHub仓库 - 工作流会自动生成,也可手动创建:
.github/workflows/azure-static-web-apps.ymlyaml
name: Azure Static Web Apps CI/CD
on:
push:
branches: [main]
pull_request:
types: [opened, synchronize, reopened, closed]
branches: [main]
jobs:
build_and_deploy:
if: github.event_name == 'push' || (github.event_name == 'pull_request' && github.event.action != 'closed')
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Build And Deploy
uses: Azure/static-web-apps-deploy@v1
with:
azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN }}
repo_token: ${{ secrets.GITHUB_TOKEN }}
action: upload
app_location: /
api_location: api
output_location: dist
close_pr:
if: github.event_name == 'pull_request' && github.event.action == 'closed'
runs-on: ubuntu-latest
steps:
- uses: Azure/static-web-apps-deploy@v1
with:
azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN }}
action: close- 添加密钥: 将部署令牌复制到仓库密钥
AZURE_STATIC_WEB_APPS_API_TOKEN
工作流设置:
- - 前端源码路径
app_location - - API源码路径
api_location - - 构建输出文件夹
output_location - - 若已预构建则跳过
skip_app_build: true - - 自定义构建命令
app_build_command
Troubleshooting
故障排除
| Issue | Solution |
|---|---|
| 404 on client routes | Add |
| API returns 404 | Verify |
| Build output not found | Verify |
| Auth not working locally | Use |
| CORS errors | APIs under |
| Deployment token expired | Regenerate in Azure Portal → Static Web App → Manage deployment token |
| Config not applied | Ensure |
| Local API timeout | Default is 45 seconds; optimize function or check for blocking calls |
Debug commands:
bash
swa start --verbose log # Verbose output
swa deploy --dry-run # Preview deployment
swa --print-config # Show resolved configuration| 问题 | 解决方案 |
|---|---|
| 客户端路由返回404 | 在 |
| API返回404 | 验证 |
| 找不到构建输出 | 验证 |
| 本地身份验证不工作 | 使用 |
| CORS错误 | |
| 部署令牌过期 | 在Azure门户 → 静态Web应用 → 管理部署令牌中重新生成 |
| 配置未生效 | 确保 |
| 本地API超时 | 默认超时为45秒;优化函数或检查是否存在阻塞调用 |
调试命令:
bash
swa start --verbose log # 详细输出
swa deploy --dry-run # 预览部署
swa --print-config # 显示解析后的配置