DEV Community

Gavi Narra
Gavi Narra

Posted on

How to setup .NET Core Blazor Server with Tailwind CSS

mkdir TailwindDotNet
cd TailwindDotNet
dotnet new blazorserver
npm init -y
npm install -D tailwindcss autoprefixer postcss
npx tailwind init -p
Enter fullscreen mode Exit fullscreen mode

Edit package.json and add a run script for CSS generation

"scripts": {
    "css:build": "npx tailwind build ./wwwroot/css/site.css -o ./wwwroot/css/output.css"
  },
Enter fullscreen mode Exit fullscreen mode

Delete bootstrap stuff

Image description

You site.css should include only the following lines

/*! @import */
@tailwind base;
@tailwind components;
@tailwind utilities;
Enter fullscreen mode Exit fullscreen mode

Add the following lines in tailwind.config.js

'./Pages/**/*.cshtml',
'./Pages/**/*.razor',
'./Views/**/*.chstml',
'./Views/**/*.razor',
'./Shared/**/*.razor',
Enter fullscreen mode Exit fullscreen mode

Modify your .csproj to include a css build step

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
  <ItemGroup>
        <UpToDateCheckBuilt Include="wwwroot/css/site.css" Set="Css" />
        <UpToDateCheckBuilt Include="postcss.config.js" Set="Css" />
        <UpToDateCheckBuilt Include="tailwind.config.js" Set="Css" />
    </ItemGroup>

    <Target Name="Tailwind" BeforeTargets="Build">
        <Exec Command="npm run css:build"/>
    </Target>

</Project>

Enter fullscreen mode Exit fullscreen mode

Modify _Layout.cshtml to reference output.css instead of site.css and remove any bootstrap references

    <link href="css/output.css" rel="stylesheet" />
Enter fullscreen mode Exit fullscreen mode

So now when you compile and run, it will build the output.css

Working with dotnet watch

Just run in a terminal window

npx tailwind build ./wwwroot/css/site.css -o ./wwwroot/css/output.css --watch
Enter fullscreen mode Exit fullscreen mode

Then run dotnet watch

dotnet watch run
Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (2)

Collapse
 
namvvo profile image
namvvo

thanks alot. but I wonder how to get it to work for Blazor.Client in new blazor web template (dotnet 8 rc2)

Collapse
 
caseyspaulding profile image
Casey Spaulding

Thank you.