mcpField
A
azure-static-web-apps

azure-static-web-apps

github.com/github云与 DevOps40.5k8.9k 次安装今天更新
代码仓库

关于 azure-static-web-apps

azure-static-web-apps 是用于 Azure Static Web Apps 的命令行工具技能,涵盖前端与可选无服务器 API 的本地开发和部署。它包括项目初始化、模拟器、构建、部署及数据库连接配置的操作说明。

主要功能

  1. 01自动检测框架并初始化配置
  2. 02本地模拟前端、API 和身份验证
  3. 03构建前端与 API
  4. 04部署到 Azure Static Web Apps
  5. 05初始化数据库连接

适用场景

  1. 01本地测试静态网站和 API
  2. 02将前端项目部署到 Azure
  3. 03配置 Azure Static Web Apps 数据库连接

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/github/awesome-copilot --skill azure-static-web-apps

安装后在 Claude Code 中输入/azure-static-web-apps确认已加载。

详细介绍

概述

Azure Static Web Apps (SWA) 用于托管静态前端,并可选择搭配无服务器 API 后端。SWA CLI (swa) 提供本地开发模拟和部署能力。

主要功能:

  • 带 API 代理和身份验证模拟的本地模拟器
  • 框架自动检测和配置
  • 直接部署到 Azure
  • 支持数据库连接

配置文件:

  • swa-cli.config.json - CLI 设置,由 swa init 创建(切勿手动创建)
  • staticwebapp.config.json - 运行时配置(路由、身份验证、标头、API 运行时)- 可手动创建

通用说明

安装
npm install -D @azure/static-web-apps-cli

验证:npx swa --version

快速入门工作流

重要:务必使用 swa init 创建配置文件。切勿手动创建 swa-cli.config.json。

  1. swa init - 必需的第一步 - 自动检测框架并创建 swa-cli.config.json
  2. swa start - 在 http://localhost:4280 运行本地模拟器
  3. swa login - 通过 Azure 进行身份验证
  4. swa deploy - 部署到 Azure
配置文件

swa-cli.config.json - 由 swa init 创建,请勿手动创建:

  • 运行 swa init 进行带框架检测的交互式设置
  • 运行 swa init --yes 接受自动检测的默认值
  • 仅在初始化后自定义设置时,才编辑生成的文件

生成的配置示例(仅供参考):

{
  "$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(位于应用源文件夹或输出文件夹中)- 此文件可手动创建,用于运行时配置:

{
  "navigationFallback": {
    "rewrite": "/index.html",
    "exclude": ["/images/*", "/css/*"]
  },
  "routes": [
    { "route": "/api/*", "allowedRoles": ["authenticated"] }
  ],
  "platform": {
    "apiRuntime": "node:20"
  }
}

命令行参考

swa login

通过 Azure 进行身份验证,以便部署。

swa login                              # Interactive login
swa login --subscription-id <id>       # Specific subscription
swa login --clear-credentials          # Clear cached credentials

标志: --subscription-id, -S | --resource-group, -R | --tenant-id, -T | --client-id, -C | --client-secret, -CS | --app-name, -n

swa init

基于现有前端和(可选)API 配置新的 SWA 项目。自动检测框架。

swa init                    # Interactive setup
swa init --yes              # Accept defaults
swa build

构建前端和/或 API。

swa build                   # Build using config
swa build --auto            # Auto-detect and build
swa build myApp             # Build specific configuration

标志: --app-location, -a | --api-location, -i | --output-location, -O | --app-build-command, -A | --api-build-command, -I

swa start

启动本地开发模拟器。

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 server

常见框架端口:

框架端口
React/Vue/Next.js3000
Angular4200
Vite5173

关键标志:

  • --port, -p - 模拟器端口(默认:4280)
  • --api-location, -i - API 文件夹路径
  • --api-port, -j - API 端口(默认:7071)
  • --run, -r - 用于启动开发服务器的命令
  • --open, -o - 自动打开浏览器
  • --ssl, -s - 启用 HTTPS
swa deploy

部署到 Azure Static Web Apps。

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 deploying

获取部署令牌:

  • Azure 门户:Static Web App → 概述 → 管理部署令牌
  • CLI:swa deploy --print-token
  • 环境变量:SWA_CLI_DEPLOYMENT_TOKEN

关键标志:

  • --env - 目标环境(preview 或 production)
  • --deployment-token, -d - 部署令牌
  • --app-name, -n - Azure SWA 资源名称
swa db

初始化数据库连接。

swa db init --database-type mssql
swa db init --database-type postgresql
swa db init --database-type cosmosdb_nosql

场景

基于现有前端和后端创建 SWA

务必在 swa start 或 swa deploy 之前运行 swa init。请勿手动创建 swa-cli.config.json。

# 1. Install CLI
npm install -D @azure/static-web-apps-cli

# 2. Initialize - REQUIRED: creates swa-cli.config.json with auto-detected settings
npx swa init              # Interactive mode
# OR
npx swa init --yes        # Accept auto-detected defaults

# 3. Build application (if needed)
npm run build

# 4. Test locally (uses settings from swa-cli.config.json)
npx swa start

# 5. Deploy
npx swa login
npx swa deploy --env production
添加 Azure Functions 后端
  1. 创建 API 文件夹:
mkdir api && cd api
func init --worker-runtime node --model V4
func new --name message --template "HTTP trigger"
  1. 示例函数(api/src/functions/message.js):
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}!` } };
    }
});
  1. 在 staticwebapp.config.json 中设置 API 运行时:
{
  "platform": { "apiRuntime": "node:20" }
}
  1. 在 swa-cli.config.json 中更新 CLI 配置:
{
  "configurations": {
    "app": { "apiLocation": "api" }
  }
}
  1. 在本地测试:
npx swa start ./dist --api-location ./api
# Access API at http://localhost:4280/api/message

支持的 API 运行时: node:18、node:20、node:22、dotnet:8.0、dotnet-isolated:8.0、python:3.10、python:3.11

设置 GitHub Actions 部署
  1. 创建 SWA 资源:在 Azure Portal 中或通过 Azure CLI 创建
  2. 关联 GitHub 仓库 - 工作流会自动生成,也可以手动创建:

.github/workflows/azure-static-web-apps.yml:

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
  1. 添加机密: 将部署令牌复制到仓库机密 AZURE_STATIC_WEB_APPS_API_TOKEN

工作流设置:

  • app_location - 前端源码路径
  • api_location - API 源码路径
  • output_location - 构建输出文件夹
  • skip_app_build: true - 如果已预构建则跳过
  • app_build_command - 自定义构建命令

故障排除

问题解决方案
客户端路由出现 404在 staticwebapp.config.json 中添加带 rewrite: "/index.html" 的 navigationFallback
API 返回 404检查 api 文件夹结构,确保已设置 platform.apiRuntime,检查函数导出
找不到构建输出确认 output_location 与实际构建输出目录一致
本地认证不工作使用 /.auth/login/<provider> 访问认证模拟器 UI
CORS 错误/api/* 下的 API 为同源;外部 API 需要 CORS 标头
部署令牌已过期在 Azure Portal → Static Web App → Manage deployment token 中重新生成
配置未生效确保 staticwebapp.config.json 位于 app_location 或 output_location 中
本地 API 超时默认是 45 秒;优化函数或检查是否存在阻塞调用

调试命令:

swa start --verbose log        # Verbose output
swa deploy --dry-run           # Preview deployment
swa --print-config             # Show resolved configuration

评论

支持 Markdown