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

including-generated-files — скилл для Claude Code

Помогает подключить файлы, созданные во время сборки, к компиляции или выходным данным MSBuild. Нужен, когда созданный файл не подхватывается автоматически.

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

Что делает including-generated-files

Скилл разбирает случаи, когда MSBuild создаёт исходник, Content, None или другой физический файл, но он не попадает в компиляцию либо каталог вывода. Он объясняет разницу между фазами вычисления и выполнения: глоб, раскрытый до запуска target, не увидит файл, появившийся позже.

Для исходников .cs предлагает добавлять путь в Compile и FileWrites внутри target с BeforeTargets="CoreCompile;BeforeCompile". Для обычных файлов используются None или Content, а время запуска выбирается между BeforeBuild и AssignTargetPaths. Глоб внутри target может захватить уже созданные файлы.

Сгенерированные артефакты следует размещать от $(IntermediateOutputPath) и регистрировать в FileWrites, чтобы Clean их удалял. Указывать obj\ вручную — плохая идея, потому что промежуточный каталог может быть переназначен. Скилл не предназначен для внутренних механизмов генераторов Roslyn и задач вне MSBuild.

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

  • подключить созданный .cs-файл к компиляции
  • добавить файл данных в каталог вывода
  • исправить глоб, который не видит файл после запуска сборки
  • выбрать BeforeTargets для созданного артефакта
  • зарегистрировать файлы для удаления через Clean

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

  • Разберись, почему созданный во время сборки .cs-файл не компилируется в MSBuild.
  • Добавь созданный файл в Compile и настрой target перед CoreCompile.
  • Как поместить созданный файл в $(IntermediateOutputPath) и удалить его через Clean?

Как установить including-generated-files

1Через Skills CLI (Vercel)

npx skills add dotnet/skills --skill including-generated-files -a claude-code

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

~/.claude/skills/including-generated-files/SKILL.md

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

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

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

generate-testability-wrappers Скилл генерирует обёртки и регистрацию в DI для статических зависимостей C#, из-за которых код не получается покрыть тестами. CX Codex +1 3 300установок nuget-trusted-publishing Настраивает публикацию пакетов в nuget.org через GitHub Actions и OIDC без постоянных API-ключей. Пригодится при переводе сборки на NuGet/login или создании нового пайплайна. CX Codex +1 3 300установок resolve-project-references Помогает не оптимизировать ResolveProjectReferences по вводящей в заблуждение метрике MSBuild. Нужен при разборе медленной сборки с binlog. CX Codex +1 3 300установок migrate-dotnet8-to-dotnet9 Скилл ведёт проект с net8.0 на net9.0: правит TargetFramework, разбирает ошибки сборки и поведенческие изменения .NET 9, C# 13, ASP.NET Core 9 и EF Core 9. CX Codex +1 3 400установок clr-activation-debugging Скилл читает логи активации CLR от mscoree.dll и показывает, какую версию рантайма выбрал шим и на каком шаге выбор сломался. CX Codex +1 3 400установок mtp-hot-reload Настраивает горячую перезагрузку тестов в консольном хосте Microsoft Testing Platform и перезапускает их после правок кода. CX Codex +1 3 400установок template-validation Скилл проверяет файлы манифестов template.json для шаблонов dotnet new. Находит синтаксические ошибки, конфликты имён и сбои в параметрах до публикации пакета в NuGet. CX Codex +1 3 200установок maui-theming Скилл подсказывает агенту, как добавить светлую и тёмную тему в .NET MAUI: AppThemeBinding, подмена ResourceDictionary, реакция на смену системной темы. CX Codex +1 3 200установок

Похожие

project-structure codewithmukesh Скилл задаёт агенту правила раскладки .NET-решения: центральные версии пакетов, общие свойства сборки, формат .slnx и именование проектов. CX Codex +1 2 800установок build-fix codewithmukesh Запускает автономный цикл починки сборки и тестов в проектах на .NET. Скилл разбирает ошибки компилятора, исправляет код и останавливается при регрессиях. CX Codex +1 2 800установок dotnet-project-structure Aaronontheweb Скилл подсказывает агенту, как разложить .NET-решение: .slnx, Directory.Build.props, центральные версии пакетов и SourceLink. CX Codex +1 658установок .NET Upgrade официальный github Ведёт проект через апгрейд .NET: находит текущие TargetFramework, строит план и обновляет проекты по одному. Пригодится, когда решение застряло на старом фреймворке. ★ 40 418звёзд репо dotnet-best-practices официальный github Проверяет выделенный .NET/C# код по правилам проекта: от структуры и DI до тестов, логирования и безопасности. Нужен при ревью или доработке решения. 15 752установок csharp-developer https://github.com/Jeffallan Настраивает правила разработки на .NET 8 и C# 12 для создания API, Blazor-приложений и работы с EF Core. Пригодится при проектировании сервисов с CQRS и Result pattern. CX Codex +1 4 800установок

Рядом в теме «Языки программирования»

Все скиллы по теме «Языки программирования» →

Вопросы о including-generated-files

Как установить including-generated-files в Claude Code?

Выполните npx skills add dotnet/skills --skill including-generated-files -a claude-code, затем повторите npx skills add dotnet/skills --skill including-generated-files -a claude-code. Файл скилла находится в ~/.claude/skills/including-generated-files/SKILL.md.

Что делает including-generated-files?

Скилл помогает включать созданные во время сборки файлы в процесс MSBuild. Он рассматривает элементы Compile, Content, None, порядок target и очистку через FileWrites.

Когда нужен BeforeTargets="CoreCompile;BeforeCompile"?

Этот момент запуска предназначен для созданных исходников, которые добавляются в Compile. Target выполняется перед компилятором, когда файл уже должен существовать.

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

SKILL.md · MIT
---
name: including-generated-files
description: "Own MSBuild generated-artifact integration. USE FOR: a target that creates or should create source, Content, None, or another physical file but the artifact is missing from compilation or output; target timing; evaluation-time glob misses; $(IntermediateOutputPath) placement; and FileWrites clean tracking. The prompt may describe the generated artifact without naming the producing task. DO NOT USE when the primary defect is general Include/Remove/Update semantics, item metadata or batching, duplicate/overlapping declarations, or a generated-item identity relationship; use item-management. Exclude Roslyn source-generator internals and non-MSBuild systems."
license: MIT
---

# Including Generated Files Into Your Build

## Overview

Files generated during the build are generally ignored by the build process. This leads to confusing results such as:
- Generated files not being included in the output directory
- Generated source files not being compiled
- Globs not capturing files created during the build

This happens because of how MSBuild's build phases work.

## Quick Takeaway

For code files generated during the build - we need to add those to `Compile` and `FileWrites` item groups within the target generating the file(s):

```xml
  <ItemGroup>
    <Compile Include="$(GeneratedFilePath)" />
    <FileWrites Include="$(GeneratedFilePath)" />
  </ItemGroup>
```

The target generating the file(s) should be hooked before CoreCompile and BeforeCompile targets - `BeforeTargets="CoreCompile;BeforeCompile"`

## Why Generated Files Are Ignored

For detailed explanation, see [How MSBuild Builds Projects](https://docs.microsoft.com/visualstudio/msbuild/build-process-overview).

### Evaluation Phase

MSBuild reads your project, imports everything, creates Properties, expands globs for Items **outside of Targets**, and sets up the build process.

### Execution Phase

MSBuild runs Targets & Tasks with the provided Properties & Items to perform the build.

**Key Takeaway:** Files generated during execution don't exist during evaluation, therefore they aren't found. This particularly affects files that are globbed by default, such as source files (`.cs`).

## Solution: Manually Add Generated Files

When files are generated during the build, manually add them into the build process. The approach depends on the type of file being generated.

### Use `$(IntermediateOutputPath)` for Generated File Location

Always use `$(IntermediateOutputPath)` as the base directory for generated files. **Do not** hardcode `obj\` or construct the intermediary path manually (e.g., `obj\$(Configuration)\$(TargetFramework)\`). The intermediate output path can be redirected to a different location in some build configurations (e.g., shared output directories, CI environments). Using `$(IntermediateOutputPath)` ensures your target works correctly regardless of the actual path.

### Always Add Generated Files to `FileWrites`

Every generated file should be added to the `FileWrites` item group. This ensures that MSBuild's `Clean` target properly removes your generated files. Without this, generated files will accumulate as stale artifacts across builds.

```xml
<ItemGroup>
  <FileWrites Include="$(IntermediateOutputPath)my-generated-file.xyz" />
</ItemGroup>
```

### Basic Pattern (Non-Code Files)

For generated files that need to be copied to output (config files, data files, etc.), add them to `Content` or `None` items before `BeforeBuild`:

```xml
<Target Name="IncludeGeneratedFiles" BeforeTargets="BeforeBuild">
  
  <!-- Your logic that generates files goes here -->

  <ItemGroup>
    <None Include="$(IntermediateOutputPath)my-generated-file.xyz" CopyToOutputDirectory="PreserveNewest"/>
    
    <!-- Capture all files of a certain type with a glob -->
    <None Include="$(IntermediateOutputPath)generated\*.xyz" CopyToOutputDirectory="PreserveNewest"/>

    <!-- Register generated files for proper cleanup -->
    <FileWrites Include="$(IntermediateOutputPath)my-generated-file.xyz" />
    <FileWrites Include="$(IntermediateOutputPath)generated\*.xyz" />
  </ItemGroup>
</Target>
```

### For Generated Source Files (Code That Needs Compilation)

If you're generating `.cs` files that need to be compiled, use **`BeforeTargets="CoreCompile;BeforeCompile"`**. This is the correct timing for adding `Compile` items — it runs late enough that the file generation has occurred, but before the compiler runs. Using `BeforeBuild` is too early for some scenarios and may not work reliably with all SDK features.

```xml
<Target Name="IncludeGeneratedSourceFiles" BeforeTargets="CoreCompile;BeforeCompile">
  <PropertyGroup>
    <GeneratedCodeDir>$(IntermediateOutputPath)Generated\</GeneratedCodeDir>
    <GeneratedFilePath>$(GeneratedCodeDir)MyGeneratedFile.cs</GeneratedFilePath>
  </PropertyGroup>

  <MakeDir Directories="$(GeneratedCodeDir)" />

  <!-- Your logic that generates the .cs file goes here -->

  <ItemGroup>
    <Compile Include="$(GeneratedFilePath)" />
    <FileWrites Include="$(GeneratedFilePath)" />
  </ItemGroup>
</Target>
```

Note: Specifying both `CoreCompile` and `BeforeCompile` ensures the target runs before whichever target comes first, providing robust ordering regardless of customizations in the build.

## Target Timing

Choose the `BeforeTargets` value based on the type of file being generated:

- **`BeforeTargets="BeforeBuild"`** — For non-code files added to `None` or `Content`. Runs early enough for copy-to-output scenarios.
- **`BeforeTargets="CoreCompile;BeforeCompile"`** — For generated source files added to `Compile`. Ensures the file is included before the compiler runs.
- **`BeforeTargets="AssignTargetPaths"`** — The "final stop" before `None` and `Content` items (among others) are transformed into new items. Use as a fallback if `BeforeBuild` is too early.

## Globbing Behavior

Globs behave according to **when** the glob took place:

| Glob Location | Files Captured |
|---------------|----------------|
| Outside of a target | Only files visible during Evaluation phase (before build starts) |
| Inside of a target | Files visible when the target runs (can capture generated files if timed correctly) |

This is why the solution places the `<ItemGroup>` inside a `<Target>` - the glob runs during execution when the generated files exist.

## Relevant Links

- [How MSBuild Builds Projects](https://docs.microsoft.com/visualstudio/msbuild/build-process-overview)
- [Evaluation Phase](https://docs.microsoft.com/visualstudio/msbuild/build-process-overview#evaluation-phase)
- [Execution Phase](https://docs.microsoft.com/visualstudio/msbuild/build-process-overview#execution-phase)
- [Common Item Types](https://docs.microsoft.com/visualstudio/msbuild/common-msbuild-project-items)
- [How the SDK imports items by default](https://github.com/dotnet/sdk/blob/main/src/Tasks/Microsoft.NET.Build.Tasks/targets/Microsoft.NET.Sdk.DefaultItems.props)
- [Official docs: Handle generated files](https://learn.microsoft.com/visualstudio/msbuild/customize-your-build#handle-generated-files)

© dotnet · MIT · dotnet/skills

Смотрите также

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

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