Skip to content

Instantly share code, notes, and snippets.

@Robbware
Last active September 5, 2022 15:47
Show Gist options
  • Save Robbware/b2fd5cd62f87af0c9382514181eba095 to your computer and use it in GitHub Desktop.
Save Robbware/b2fd5cd62f87af0c9382514181eba095 to your computer and use it in GitHub Desktop.
Blazor - Get component isolated SCSS files compiled into CSS and ready for Blazor CSS isolation to work

If you don't have npm initialized in your project scope, run npm init -y

  1. npm install sass --save-dev Refer to: https://sass-lang.com/documentation/

  2. Add, to your package.json, on the scripts object: "scripts": { "sass": "sass" },

  3. Create a new folder Styles, with an app.scss file there - this'll be your global styling solution

  4. On your project's .csproj, add:

Watch for SCSS file changes (when using dotnet watch - more info here):

<ItemGroup>
    <Watch Include="**\*.scss" />
    <None Update="**\*.css" watch="false" />
</ItemGroup>

Create a task to compile scss to css (before Build compilation starts) (Credits)

  <Target Name="CompileGlobalSass" BeforeTargets="Compile">
    <Message Text="Compiling global SCSS file" Importance="high" />
    <Exec Command="npm run sass Styles:wwwroot/css Pages:Pages Shared:Shared --style=compressed --no-source-map --load-path=Styles --update" />
  </Target>

Note: This'll compile your scss files onto css and keep the same name as your scss file. For the Blazor CSS isolation to work, your scss/css file must have the same name as your component. e.g.: NavMenu.razor component should have a scss file called NavMenu.razor.scss, which will be compiled onto NavMenu.razor.css and allow for CSS isolation to work.

More on Blazor CSS isolation: https://github.com/dotnet/AspNetCore.Docs/blob/main/aspnetcore/blazor/components/css-isolation.md

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment