asp.net-coremsbuilddotnet-publish

How do I run npm build as part of dotnet publish


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?


Solution

  • 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.