.netasp.net-core.net-corerazormsbuild

Hot reload with ASP.NET Core and TailwindCSS (or: adding extra command to dotnet watch)


I'm investigating a good hot-reload workflow for using TailwindCSS with ASP.NET.

I've settled on using VSCode as VisualStudio doesn't have a good tailwind extension and Rider's extension doesn't support Razor files.

There are now two competing watchers that update files:

Using them both at the same time almost works, but not quite: dotnet watch is faster and doesn't pick up the changes made by tailwindcss --watch. So you always see only the changes one time before the last time an edit was made.

I've tried adding the tailwindcss as a post-build step (it would be good enough enough if it triggeres on razor files):

<Target Name="PostBuild" AfterTargets="PostBuildEvent">
  <Exec Command="npx tailwindcss -i ./wwwroot/css/input.css -o ./wwwroot/css/output.css" />
</Target>

However, that step doesn't get executed by dotnet watch when hot reload takes place.

dotnet watch does support running a command other than run, but still only those of the dotnet tool, and I don't see a way to execute arbitrary other commands.

Does anyone have more ideas?


Solution

  • found your question and had the exact same use case. Managed to figure it out with a bit of fiddling.

    So as you've got in your .csproj:

    <Target Name="PostBuild" AfterTargets="PostBuildEvent">
      <Exec Command="npx tailwindcss -i ./wwwroot/css/input.css -o ./wwwroot/css/output.css" />
    </Target>
    

    But the next part that is missing is the hot-reload functionality. https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-watch#hot-reload specifically this section 'lets you apply changes to a running app without having to rebuild and restart it'

    So the above PostBuild step isn't being ran, and that's why there are no changes seen.

    Running dotnet watch --no-hot-reload should instead cause the app to rebuild each time, while slightly slower, at least it automates the tailwind commands.

    There is also this section in the dotnet watch docs https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-watch#advanced-configuration where I think it may be possible to trigger the command based on that ItemGroup, but I'm not a MSBuild expert and have no clue how you'd go about that.