Создавайте, настраивайте и развертывайте статические сайты с опциональным serverless API бэкендом с помощью SWA CLI.
- Звёзды на GitHub
- 41 038
- Файлы
- 1
- Последний коммит
- 11 нояб. 2026 г.
- Лицензия
- MIT
- Разрешённые инструменты
- —
Что делает навык azure-static-web-apps?
azure-static-web-apps — это Agent Skill. Создавайте, настраивайте и развертывайте статические сайты с опциональным serverless API бэкендом с помощью SWA CLI.
Сводка сгенерирована из SKILL.md навыка.
О skill azure-static-web-apps
Развертывание и управление статическими сайтами с serverless бэкендом — это то, чего разработчики добиваются с помощью этого SKILL. Он предоставляет доступ к SWA CLI для управления полным жизненным циклом Azure Static Web App: от локальной эмуляции до развертывания в продакшн. Агент должен загружать этот инструмент, когда пользователю нужно инициализировать новый проект, запустить локальный сервер разработки с проксированием API или настроить маршрутизацию и аутентификацию через staticwebapp.config.json.
Этот навык автоматизирует определение фреймворка через команду swa init, которая генерирует необходимый файл swa-cli.config.json. Он позволяет интегрировать Azure Functions в качестве уровня API и поддерживает различные подключения к базам данных, включая MSSQL, PostgreSQL и CosmosDB. Пользователи могут управлять развертыванием в продакшн или превью-среды с помощью swa deploy, а также настраивать автоматизированные CI/CD конвейеры через GitHub Actions.
Что агент может делать с ним
- 1Инициализация нового проектаНастройка нового проекта Static Web App путем автоматического определения фронтенд-фреймворка и создания конфигурационных файлов.
- 2Запуск локального эмулятораЗапуск локальной среды разработки, которая имитирует хостинг-среду и проксирование API.
- 3Развертывание в AzureПуш собранного приложения и его API в среду Azure Static Web App.
- 4Подключение базы данныхНастройка подключений к бэкенд-базам данных, таким как PostgreSQL или CosmosDB.
Написано на основе skill SKILL.md. Каждый сценарий использования проверен по цитате из него.
Как установить навык azure-static-web-apps
Каждая команда копирует папку навыка в каталог навыков клиента. Перезапустите клиент или начните новую сессию, чтобы загрузить его.Установка навыка azure-static-web-apps в Claude Code
~/.claude/skills/azure-static-web-apps/SKILL.md
$ npx degit github/awesome-copilot/skills/azure-static-web-apps ~/.claude/skills/azure-static-web-appsУстановка навыка azure-static-web-apps в Claude Code (project)
.claude/skills/azure-static-web-apps/SKILL.md
$ npx degit github/awesome-copilot/skills/azure-static-web-apps .claude/skills/azure-static-web-appsУстановка навыка azure-static-web-apps в Codex
~/.agents/skills/azure-static-web-apps/SKILL.md
$ npx degit github/awesome-copilot/skills/azure-static-web-apps ~/.agents/skills/azure-static-web-appsУстановка навыка azure-static-web-apps в Gemini CLI
~/.gemini/skills/azure-static-web-apps/SKILL.md
$ npx degit github/awesome-copilot/skills/azure-static-web-apps ~/.gemini/skills/azure-static-web-appsУстановка навыка azure-static-web-apps в Claude.ai
npx degit github/awesome-copilot/skills/azure-static-web-apps azure-static-web-apps && zip -r azure-static-web-apps.zip azure-static-web-apps # claude.ai → Customize → Skills → + → Create skill → Upload a skill → azure-static-web-apps.zip
Автоматические проверки
Запущено 15 нояб. 2026 г.Полный отчёт →Прошёл наши автоматические проверки. Это не аудит безопасности: прочитайте скрипты, прежде чем агент их запустит. Как работают проверки
- Связанный и доступный исходный репозиторийgithub/awesome-copilot/skills/azure-static-web-apps is public and reachablegithub.com/github/awesome-copilot/tree/HEAD/skills/azure-sta ↗Пройдено
- Open source лицензия (OSI)MITspdx.org/licenses/MIT.html ↗Пройдено
- Коммит или релиз за последний годLast commit 2026-11-11github.com/github/awesome-copilot/commits ↗Пройдено
- В скриптах нет загрузки с запуском и кражи учётных данныхNo scripts in the skill folderПройдено
- В SKILL.md нет скрытых инструкцийNo override phrases, safeguard switches, credential requests or hidden charactersgithub.com/github/awesome-copilot/blob/HEAD/skills/azure-sta ↗Пройдено
- Заранее разрешённые инструменты ограниченыNo pre-approved tools; the agent asks before using onegithub.com/github/awesome-copilot/blob/HEAD/skills/azure-sta ↗Пройдено
- SKILL.md соответствует формату Agent SkillsValid name and description; says when to use it; 316 linesgithub.com/github/awesome-copilot/blob/HEAD/skills/azure-sta ↗Пройдено
SKILL.md
Открыть на GitHubOverview
Azure Static Web Apps (SWA) hosts static frontends with optional serverless API backends. The SWA CLI (swa) provides local development emulation and deployment capabilities.
Key features:
- Local emulator with API proxy and auth simulation
- Framework auto-detection and configuration
- Direct deployment to Azure
- Database connections support
Config files:
swa-cli.config.json- CLI settings, created byswa init(never create manually)staticwebapp.config.json- Runtime config (routes, auth, headers, API runtime) - can be created manually
General Instructions
Installation
npm install -D @azure/static-web-apps-cli
Verify: npx swa --version
Quick Start Workflow
IMPORTANT: Always use swa init to create configuration files. Never manually create swa-cli.config.json.
swa init- Required first step - auto-detects framework and createsswa-cli.config.jsonswa start- Run local emulator athttp://localhost:4280swa login- Authenticate with Azureswa deploy- Deploy to Azure
Configuration Files
swa-cli.config.json - Created by swa init, do not create manually:
- Run
swa initfor interactive setup with framework detection - Run
swa init --yesto accept auto-detected defaults - Edit the generated file only to customize settings after initialization
Example of generated config (for reference only):
{
"$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:
{
"navigationFallback": {
"rewrite": "/index.html",
"exclude": ["/images/*", "/css/*"]
},
"routes": [
{ "route": "/api/*", "allowedRoles": ["authenticated"] }
],
"platform": {
"apiRuntime": "node:20"
}
}
Command-line Reference
swa login
Authenticate with Azure for deployment.
swa login # Interactive login
swa login --subscription-id <id> # Specific subscription
swa login --clear-credentials # Clear cached credentials
Flags: --subscription-id, -S | --resource-group, -R | --tenant-id, -T | --client-id, -C | --client-secret, -CS | --app-name, -n
swa init
Configure a new SWA project based on an existing frontend and (optional) API. Detects frameworks automatically.
swa init # Interactive setup
swa init --yes # Accept defaults
swa build
Build frontend and/or API.
swa build # Build using config
swa build --auto # Auto-detect and build
swa build myApp # Build specific configuration
Flags: --app-location, -a | --api-location, -i | --output-location, -O | --app-build-command, -A | --api-build-command, -I
swa start
Start local development emulator.
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
Common framework ports:
| Framework | Port |
|---|---|
| React/Vue/Next.js | 3000 |
| Angular | 4200 |
| Vite | 5173 |
Key flags:
--port, -p- Emulator port (default: 4280)--api-location, -i- API folder path--api-port, -j- API port (default: 7071)--run, -r- Command to start dev server--open, -o- Open browser automatically--ssl, -s- Enable HTTPS
swa deploy
Deploy to 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
Get deployment token:
- Azure Portal: Static Web App → Overview → Manage deployment token
- CLI:
swa deploy --print-token - Environment variable:
SWA_CLI_DEPLOYMENT_TOKEN
Key flags:
--env- Target environment (previeworproduction)--deployment-token, -d- Deployment token--app-name, -n- Azure SWA resource name
swa db
Initialize database connections.
swa db init --database-type mssql
swa db init --database-type postgresql
swa db init --database-type cosmosdb_nosql
Scenarios
Create SWA from Existing Frontend and Backend
Always run swa init before swa start or swa deploy. Do not manually create 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
Add Azure Functions Backend
- Create API folder:
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):
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:
{
"platform": { "apiRuntime": "node:20" }
}
- Update CLI config in
swa-cli.config.json:
{
"configurations": {
"app": { "apiLocation": "api" }
}
}
- Test locally:
npx swa start ./dist --api-location ./api
# Access API at http://localhost:4280/api/message
Supported API runtimes: node:18, node:20, node:22, dotnet:8.0, dotnet-isolated:8.0, python:3.10, python:3.11
Set Up GitHub Actions Deployment
- 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.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
- Add secret: Copy deployment token to repository secret
AZURE_STATIC_WEB_APPS_API_TOKEN
Workflow settings:
app_location- Frontend source pathapi_location- API source pathoutput_location- Built output folderskip_app_build: true- Skip if pre-builtapp_build_command- Custom build command
Troubleshooting
| Issue | Solution |
|---|---|
| 404 on client routes | Add navigationFallback with rewrite: "/index.html" to staticwebapp.config.json |
| API returns 404 | Verify api folder structure, ensure platform.apiRuntime is set, check function exports |
| Build output not found | Verify output_location matches actual build output directory |
| Auth not working locally | Use /.auth/login/<provider> to access auth emulator UI |
| CORS errors | APIs under /api/* are same-origin; external APIs need CORS headers |
| Deployment token expired | Regenerate in Azure Portal → Static Web App → Manage deployment token |
| Config not applied | Ensure staticwebapp.config.json is in app_location or output_location |
| Local API timeout | Default is 45 seconds; optimize function or check for blocking calls |
Debug commands:
swa start --verbose log # Verbose output
swa deploy --dry-run # Preview deployment
swa --print-config # Show resolved configuration
Файлы в этом навыке
1Вопросы о навыке azure-static-web-apps
Как установить навык azure-static-web-apps в Claude Code?
Выполните npx degit github/awesome-copilot/skills/azure-static-web-apps ~/.claude/skills/azure-static-web-apps. Claude Code загружает навыки из ~/.claude/skills (все проекты) или .claude/skills (один проект) и использует навык, когда его описание соответствует задаче.
Какие клиенты могут использовать навык azure-static-web-apps?
Любой клиент, который читает формат Agent Skills: Claude Code, Codex, Gemini CLI и claude.ai (загрузить как ZIP). Скрипты в навыке выполняются только там, где клиент разрешает выполнение кода.
Как создать конфигурационные файлы для нового проекта SWA?
Всегда используйте команду swa init, чтобы автоматически определить ваш фреймворк и создать файл swa-cli.config.json. Никогда не создавайте этот файл вручную.
Могу ли я вручную создать конфигурационный файл для настроек среды выполнения?
Да, вы можете вручную создать файл staticwebapp.config.json в папке с исходным кодом или в папке вывода приложения для управления маршрутами, аутентификацией и заголовками.
Как исправить ошибки 404 на клиентских маршрутах?
Чтобы устранить ошибки 404 на клиентских маршрутах, добавьте navigationFallback с перенаправлением (rewrite) на /index.html в ваш файл staticwebapp.config.json.