К основному содержанию
скилл CX Codex

playwright-ci-caching — скилл для Claude Code: как установить

Настраивает кэширование браузеров Playwright в GitHub Actions и Azure DevOps. Устраняет лишнюю загрузку ~400MB бинарников и сокращает сборку на 1-2 минуты в .NET-проектах.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add Aaronontheweb/dotnet-skills --skill playwright-ci-caching -a claude-code
Открыть на GitHub

Что делает playwright-ci-caching

Скилл внедряет конфигурацию кэширования для E2E-тестов Playwright. Он считывает версию пакета Microsoft.Playwright из файла Directory.Packages.props и использует её как часть ключа кэша. Сами браузеры скачиваются только при промахе кэша через скрипт build/playwright.ps1 install --with-deps.

Шаблон учитывает пути к каталогу ms-playwright для Linux, macOS и Windows. В комплект входит вспомогательный PowerShell-скрипт build/playwright.ps1, который находит библиотеку Microsoft.Playwright.dll после сборки проекта и вызывает системный CLI Playwright.

Если в проекте не включён Central Package Management (CPM), шаг извлечения версии сломается из-за отсутствия Directory.Packages.props. Привязка ключа к номеру версии пакета исключает рассинхронизацию SDK и бинарников, поэтому ручная очистка кэша после обновлений не требуется.

Какие задачи решает

  • сократить время прогона CI/CD при тестировании через Playwright
  • настроить сохранение бинарников браузеров в кэш GitHub Actions и Azure DevOps
  • автоматизировать инвалидацию кэша при обновлении Microsoft.Playwright
  • запускать Playwright CLI через единый PowerShell-скрипт после сборки dotnet

Примеры запросов агенту

  • Настрой кэширование браузеров Playwright в GitHub Actions через Directory.Packages.props
  • Создай скрипт build/playwright.ps1 и шаги кэша для Azure DevOps pipeline

Как установить playwright-ci-caching

1Через Skills CLI (Vercel)

npx skills add Aaronontheweb/dotnet-skills --skill playwright-ci-caching -a claude-code

2Вручную: положить файлы

~/.claude/skills/playwright-ci-caching/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/playwright-ci-caching/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о playwright-ci-caching

Как установить playwright-ci-caching в Claude Code?

Выполните команду npx skills add Aaronontheweb/dotnet-skills --skill playwright-ci-caching -a claude-code.

Зачем нужен playwright-ci-caching?

Он исключает постоянное скачивание браузеров объёмом ~400MB при каждом прогоне CI, сохраняя файлы в кэш и экономя 1-2 минуты.

Что требуется для работы этого шаблона?

Необходим Central Package Management с файлом Directory.Packages.props, доступность PowerShell на агенте CI и предварительный вызов dotnet build.

Исходный текст

SKILL.md · MIT
---
name: playwright-ci-caching
description: Cache Playwright browser binaries in CI/CD pipelines (GitHub Actions, Azure DevOps) to avoid 1-2 minute download overhead on every build.
user-invocable: false
---

# Caching Playwright Browsers in CI/CD

## When to Use This Skill

Use this skill when:
- Setting up CI/CD for a project with Playwright E2E tests
- Build times are slow due to browser downloads (~400MB, 1-2 minutes)
- You want automatic cache invalidation when Playwright version changes
- Using GitHub Actions or Azure DevOps pipelines

## The Problem

Playwright browsers (~400MB) must be downloaded on every CI run by default. This:
- Adds 1-2 minutes to every build
- Wastes bandwidth
- Can fail on transient network issues
- Slows down PR feedback loops

## Core Pattern

1. **Extract Playwright version** from `Directory.Packages.props` (CPM) to use as cache key
2. **Cache browser binaries** using platform-appropriate paths
3. **Conditional install** - only download on cache miss
4. **Automatic cache bust** - key includes version, so package upgrades invalidate cache

## Cache Paths by OS

| OS | Path |
|----|------|
| Linux | `~/.cache/ms-playwright` |
| macOS | `~/Library/Caches/ms-playwright` |
| Windows | `%USERPROFILE%\AppData\Local\ms-playwright` |

## GitHub Actions

```yaml
- name: Get Playwright Version
  shell: pwsh
  run: |
    $propsPath = "Directory.Packages.props"
    [xml]$props = Get-Content $propsPath
    $version = $props.Project.ItemGroup.PackageVersion |
      Where-Object { $_.Include -eq "Microsoft.Playwright" } |
      Select-Object -ExpandProperty Version
    echo "PlaywrightVersion=$version" >> $env:GITHUB_ENV

- name: Cache Playwright Browsers
  id: playwright-cache
  uses: actions/cache@v4
  with:
    path: ~/.cache/ms-playwright
    key: ${{ runner.os }}-playwright-${{ env.PlaywrightVersion }}

- name: Install Playwright Browsers
  if: steps.playwright-cache.outputs.cache-hit != 'true'
  shell: pwsh
  run: ./build/playwright.ps1 install --with-deps
```

### Multi-OS GitHub Actions

For workflows that run on multiple operating systems:

```yaml
- name: Cache Playwright Browsers
  id: playwright-cache
  uses: actions/cache@v4
  with:
    path: |
      ~/.cache/ms-playwright
      ~/Library/Caches/ms-playwright
      ~/AppData/Local/ms-playwright
    key: ${{ runner.os }}-playwright-${{ env.PlaywrightVersion }}
```

## Azure DevOps

```yaml
- task: PowerShell@2
  displayName: 'Get Playwright Version'
  inputs:
    targetType: 'inline'
    script: |
      [xml]$props = Get-Content "Directory.Packages.props"
      $version = $props.Project.ItemGroup.PackageVersion |
        Where-Object { $_.Include -eq "Microsoft.Playwright" } |
        Select-Object -ExpandProperty Version
      Write-Host "##vso[task.setvariable variable=PlaywrightVersion]$version"

- task: Cache@2
  displayName: 'Cache Playwright Browsers'
  inputs:
    key: 'playwright | "$(Agent.OS)" | $(PlaywrightVersion)'
    path: '$(HOME)/.cache/ms-playwright'
    cacheHitVar: 'PlaywrightCacheHit'

- task: PowerShell@2
  displayName: 'Install Playwright Browsers'
  condition: ne(variables['PlaywrightCacheHit'], 'true')
  inputs:
    filePath: 'build/playwright.ps1'
    arguments: 'install --with-deps'
```

## Helper Script: playwright.ps1

Create a `build/playwright.ps1` script that discovers and runs the Playwright CLI. This abstracts away the Playwright CLI location which varies by project structure.

```powershell
# build/playwright.ps1
# Discovers Microsoft.Playwright.dll and runs the bundled Playwright CLI

param(
    [Parameter(ValueFromRemainingArguments = $true)]
    [string[]]$Arguments
)

# Find the Playwright DLL (after dotnet build/restore)
$playwrightDll = Get-ChildItem -Path . -Recurse -Filter "Microsoft.Playwright.dll" -ErrorAction SilentlyContinue |
    Select-Object -First 1

if (-not $playwrightDll) {
    Write-Error "Microsoft.Playwright.dll not found. Run 'dotnet build' first."
    exit 1
}

$playwrightDir = $playwrightDll.DirectoryName

# Find the playwright CLI (path varies by OS and node version)
$playwrightCmd = Get-ChildItem -Path "$playwrightDir/.playwright/node" -Recurse -Filter "playwright.cmd" -ErrorAction SilentlyContinue |
    Select-Object -First 1

if (-not $playwrightCmd) {
    # Try Unix executable
    $playwrightCmd = Get-ChildItem -Path "$playwrightDir/.playwright/node" -Recurse -Filter "playwright" -ErrorAction SilentlyContinue |
        Where-Object { $_.Name -eq "playwright" } |
        Select-Object -First 1
}

if (-not $playwrightCmd) {
    Write-Error "Playwright CLI not found in $playwrightDir/.playwright/node"
    exit 1
}

Write-Host "Using Playwright CLI: $($playwrightCmd.FullName)"
& $playwrightCmd.FullName @Arguments
```

Usage:
```bash
# Install browsers
./build/playwright.ps1 install --with-deps

# Install specific browser
./build/playwright.ps1 install chromium

# Show installed browsers
./build/playwright.ps1 install --dry-run
```

## Prerequisites

This pattern assumes:

1. **Central Package Management (CPM)** with `Directory.Packages.props`:
   ```xml
   <Project>
     <ItemGroup>
       <PackageVersion Include="Microsoft.Playwright" Version="1.40.0" />
     </ItemGroup>
   </Project>
   ```

2. **Project has been built** before running `playwright.ps1` (so DLLs exist)

3. **PowerShell available** on CI agents (pre-installed on GitHub Actions and Azure DevOps)

## Why Version-Based Cache Keys Matter

Using the Playwright version in the cache key ensures:

- **Automatic invalidation** when you upgrade Playwright
- **No stale browser binaries** that don't match the SDK version
- **No manual cache clearing** needed after version bumps

If you hardcode the cache key (e.g., `playwright-browsers-v1`), you'll need to manually bump it every time you upgrade Playwright, or you'll get cryptic version mismatch errors.

## Troubleshooting

### Cache not being used

1. Verify the version extraction step outputs the correct version
2. Check that the cache path matches your OS
3. Ensure `Directory.Packages.props` exists and has the Playwright package

### "Browser not found" after cache hit

The cached browsers don't match the Playwright SDK version. This happens when:
- The cache key doesn't include the version
- The version extraction failed silently

Fix: Ensure the Playwright version is in the cache key.

### playwright.ps1 can't find the DLL

Run `dotnet build` or `dotnet restore` before running the script. The Playwright DLL only exists after NuGet restore.

## References

This pattern is battle-tested in production projects:
- [petabridge/geekedin](https://github.com/petabridge/geekedin)
- [petabridge/DrawTogether.NET](https://github.com/petabridge/DrawTogether.NET)

## Related Skills

- `dotnet-skills:playwright-blazor` - Writing Playwright tests for Blazor applications
- `dotnet-skills:project-structure` - Central Package Management setup

© Aaronontheweb · MIT · Aaronontheweb/dotnet-skills

Похожие скиллы

Всё по теме «DevOps и инфраструктура» →
playwright-ci testdino-hq Скилл с готовыми конфигурациями CI/CD для Playwright: GitHub Actions, GitLab CI, CircleCI, Azure DevOps, Jenkins и Docker. Пригодится, когда тесты уже написаны, а пайплайн всё ещё падает. CX Codex +1 372установок ci-cd codewithmukesh Скилл помогает создавать YAML-пайплайны для проектов на .NET. Пригодится для быстрой настройки GitHub Actions и Azure DevOps с этапами сборки, тестов и публикации. CX Codex +1 2 800установок ci-cd-and-automation addyosmani Скилл собирает пайплайн CI/CD на GitHub Actions: линт, типы, тесты, сборка и аудит зависимостей идут по порядку с фиксированным набором гейтов на каждый PR. CX Codex +1 58 100установок ci-cd-integration kindlmann Проектирует пайплайны CI/CD для тестов с шардингом, карантином нестабильных проверок и гейтами покрытия. Помогает настроить GitHub Actions и GitLab CI под разные триггеры. CX Codex +1 1 100установок azure-devops devops-skills Скилл помогает агенту писать и править YAML-пайплайны Azure DevOps: сборка, тесты, деплой в Azure. Пригодится, если CI/CD живёт в Azure Pipelines. CX Codex +1 325установок pw-init Alireza Rezvani Настраивает Playwright для e2e-тестов в существующем проекте. Нужен, когда надо добавить тестовую инфраструктуру с конфигом, примером и запуском в CI. 15установок

Из того же набора32

mjml-email-templates Скилл учит агента собирать транзакционные письма на MJML и компилировать их в HTML, который одинаково выглядит в Outlook, Gmail и Apple Mail. CX Codex +1 492установок aspire-configuration Учит AppHost переводить ресурсы Aspire в явные ключи конфигурации, чтобы код приложения не зависел от клиентов Aspire и service discovery. CX Codex +1 463установок snapshot-testing Скилл учит агента писать снапшот-тесты на Verify: вывод сравнивается с эталонным файлом, который вы утвердили вручную. CX Codex +1 461установок skills-index-snippets Собирает компактный роутер скиллов и агентов для AGENTS.md или CLAUDE.md, чтобы ассистент вызывал нужный скилл по имени, а не по памяти. CX Codex +1 435установок dotnet-devcert-trust Разбирает, почему .NET и Aspire не доверяют HTTPS-сертификату разработчика на Linux, и доводит его до системного CA-бандла. CX Codex +1 434установок akka-net-best-practices Скилл с правилами Akka.NET: когда EventStream, когда DistributedPubSub, как разводить ошибки и супервизию. Пригодится при проектировании акторов. CX Codex +1 431установок mailpit-integration Поднимает Mailpit в .NET Aspire, чтобы письма перехватывались локально, а не уходили реальным адресатам. Пригодится при отладке шаблонов и интеграционных тестах. CX Codex +1 421установок verify-email-snapshots Скилл для снапшот-тестирования HTML-писем через Verify: рендер шаблона сравнивается с утверждённым эталоном, и тест падает при расхождении. CX Codex +1 416установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой