Compile Sass Files in .NET Core

Viewed 20243

I am trying to add Sass files to my .NET Core application in Visual Studio 2017. However, I cannot find any way to compile .scss files once I've made them. I sifted through NPM and Bower, but neither offer support for Sass.

The Microsoft documentation for adding Sass (https://docs.microsoft.com/en-us/aspnet/core/client-side/less-sass-fa) is outdated, and assumes that the project has a package.json file. Any guidance on enabling Sass compiling for my project would be much appreciated.

7 Answers

The easiest way to add .scss to your ASP.NET Core apps is by going to the Nuget Package Manager and installing LigerShark.WebOptimizer.Core and LigerShark.WebOptimizer.Sass

After that, you can just put

<link rel="stylesheet" href="~/css/site.scss" />

in the head of the _Layout.cshtml file and the LigerShark.WebOptimizer.Sass package will compile all of your sass files automatically.

Use this extension for Visual Studio https://marketplace.visualstudio.com/items?itemName=MadsKristensen.WebCompiler

This extension not only lets you manually compile SASS/SCSS files to CSS, but it also adds a compilerconfig.json which can recompile your CSS every single time you click save.

Additionally, this extension can compile on project build via a nuget package it can install into your project. Which also enables CI/CD support.

This is by far the easiest way to add SCSS/SASS compilation to an ASP.NET Core Project when working inside of Visual Studio.

If you want SCSS compilation and bundling in one simple tool, try NBundle. (Apologies for the shameless self-plug!)

You specify which files to monitor (wildcards allowed) and the tool can be used to generate compiled and bundled files in a one-shot or "watcher" mode where output files are generated when the source files are saved.

You can use live SASS compiler for compiling SCSS to CSS when the build occurs. You have to add few line in the .csproj file and prior to that install live sass compiler from npm. Here is my blog post: How to Use SCSS with ASP.NET Core 5.X or 3.X

How to accomplish this might depend on your workflow. I'd like it to be part of the build process as seamlessly as possible. So my prefered solution is using a dotnet tool called excubo.webcompiler(no I'm not affiliated in any way with the author). If you install it as a project tool

dotnet tool install Excubo.WebCompiler

you can add a simple target to your project file.

<Target Name="CompileStaticAssets" AfterTargets="AfterBuild">
    <Exec Command="dotnet webcompiler -r wwwroot" StandardOutputImportance="high" />
</Target>

That will use the default settings which will often be sufficient. If not you can tweak the process using a configuration file

Related