Kyle B
Kyle B

Reputation: 2899

Visual Studio automatically removes new files from custom MSBuild Task

Is there something I am doing wrong with this custom MSBuild target to cause Visual Studio to do this behavior?

I have a custom MSBuild task that bundles separate javascript files into a single file, it's used like this in the csproj file:

<ItemGroup>
    <ScriptBundler Include="**\*.js" Exclude="app.js" />
</ItemGroup>

Problem: When I add a new myNewFile.js that matches the path in the Include, Visual Studio automatically adds this line into the csproj:

<ScriptBundler Remove="myNewFile.js" />

It usually takes me or another co-worker about an hour of debugging to figure out why my new script isn't being bundled correctly.

Question: Is there something different I can do with Include="**\*.js" to stop this from happening? Alternatively is there something I can do in the custom task to tell Visual Studio to be greedy with new files added?

The custom build task accepts input for files like this:

[Required]
public ITaskItem[] Files { get; set; }

Edit: And it is added into the project like this:

<Target Name="BeforeBuild">
  <BundleScripts Files="@(ScriptBundle)" 
                 ProjectDirectory="$(MSBuildProjectDirectory)" />
</Target>

Upvotes: 0

Views: 58

Answers (1)

Dou Xu-MSFT
Dou Xu-MSFT

Reputation: 3321

Is there something I am doing wrong with this custom MSBuild target to cause Visual Studio to do this behavior?

No, based on my test, i can reproduce the same behavior in my VS2022(17.10.4). When i add a new file to a MSBuild item, the <Remove> element is automatically added to the project file. I guess this behavior is by design and serves a specific purpose:Incremental Builds.

If you want to prevent the automatic addition of elements, here is a workaround: using Condition="'$(DesignTimeBuild)' != 'true'" in the ItemGroup.

For example:

<ItemGroup Condition="'$(DesignTimeBuild)' != 'true'">
    <ScriptBundler Include="wwwroot\js\*.js" Exclude="wwwroot\js\app.js" />
</ItemGroup>

For more information about DesignTimeBuild, please refer to doc: https://github.com/dotnet/project-system/blob/main/docs/design-time-builds.md

Upvotes: 1

Related Questions