0

I have an ASP.NET Core 8 web project, where the client source code lives in a client folder.

I also have an npm run build that will compile those client files, and copy the output to the wwwroot folder.

I would like to make the npm build part of the dotnet publish, but not the dotnet build.

Right now I have used this in my .csproj file:

<Target Name="NpmBuild" BeforeTargets="Publish">
    <Exec Command="npm ci" WorkingDirectory="client" />
    <Exec Command="npm run build" WorkingDirectory="client" />
</Target>

The npm commands are executed, but not until the publish folder has already been populated by the publish command.

What is the right way to ensure that the npm commands are run before the files are copied to the output folder?

5
  • Use the BeforeTargets="Publish" and the AfterTargets="PrepareForPublish" attributes in your .csproj file. learn.microsoft.com/en-us/visualstudio/msbuild/… Commented Jul 4 at 18:59
  • Try BeforeTargets="BeforePublish". BeforePublish is publicly documented. Commented Jul 5 at 0:39
  • 1
    @JonathanDodds This did the trick for me. Thank you. You want to add an answer I can accept, or should I post the fixed code myself?
    – mortenbock
    Commented Jul 5 at 8:59
  • The usage of BeforeTarget is correct , but it does not work as expected, why? That is because the publicly available targets don't show the entire chain. You could type in "dotnet publish -v diag" to see all the targets executed before publish. i.sstatic.net/EDlHOREZ.png As you can see in the picture, there are so many targets executed before publish, so that your code works not so correctly. In another word, the targets shown in the list could be chosen to set BeforeTargets as you wish to meet your customization design. Commented Jul 5 at 9:14
  • @FengzhiZhou The image shows the "Target Performance Summary". The ordering of the targets in the summary is not the execution order of the targets. Commented Jul 5 at 16:30

1 Answer 1

0

There are predefined targets for before and after specific steps. See the Table of predefined targets.

Among the predefined targets is a BeforePublish target. The BeforePublish target will be executed before the Publish target.

Change your NpmBuild target to use BeforeTargets="BeforePublish".

<Target Name="NpmBuild" BeforeTargets="BeforePublish">
    <Exec Command="npm ci" WorkingDirectory="client" />
    <Exec Command="npm run build" WorkingDirectory="client" />
</Target>

The documentation talks about overriding a predefined target. When there are mulitple overrides, the last override that is defined will be used. The function of the other overrides will be "lost". However, multiple targets can use BeforeTargets="BeforePublish" without conflict.

Not the answer you're looking for? Browse other questions tagged or ask your own question.