H. Pauwelyn
H. Pauwelyn

Reputation: 14320

How to use SaSS for an ASP.NET MVC application?

Problem and question

I've always had problems with CSS code, so now I always use SaSS code. But my question is: how can I use SaSS for an ASP.NET MVC application?

I've tried

I've tried tried to use a Gulp task for this. I've used these commands

npm init
npm install --save gulp
npm install --save gulp-sass

Here is my package.json file:

{
  "name": "markeonline",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Hein Pauwelyn",
  "license": "ISC",
  "dependencies": {
    "gulp": "^3.9.1",
    "gulp-sass": "^3.1.0"
  }
}

Here is the gulpfile.js

var gulp = require("gulp"),
    sass = require("gulp-sass");

// other content removed

gulp.task("sass", function () {
    return gulp.src('./**/*.scss')
      .pipe(sass())
      .pipe(gulp.dest(project.webroot + './MarkeOnline.Website/Content/css'));
});

Here is my project structure:

Solution explorer at Visual Studio

This code gives me the following error if I use the command below:

gulp sass

ReferenceError: project is not defined

[17:50:58] ReferenceError: project is not defined
    at Gulp.<anonymous> (D:\Documenten\Howest\Semester 4\05 - Project\MarkeOnlinebis\Project Execution\MarkeOnline\gulpfile.js:9:23)
    at module.exports (D:\Documenten\Howest\Semester 4\05 - Project\MarkeOnlinebis\Project Execution\MarkeOnline\node_modules\orchestrator\lib\runTask.js:34:7)
    at Gulp.Orchestrator._runTask (D:\Documenten\Howest\Semester 4\05 - Project\MarkeOnlinebis\Project Execution\MarkeOnline\node_modules\orchestrator\index.js:273:3)
    at Gulp.Orchestrator._runStep (D:\Documenten\Howest\Semester 4\05 - Project\MarkeOnlinebis\Project Execution\MarkeOnline\node_modules\orchestrator\index.js:214:10)
    at Gulp.Orchestrator.start (D:\Documenten\Howest\Semester 4\05 - Project\MarkeOnlinebis\Project Execution\MarkeOnline\node_modules\orchestrator\index.js:134:8)
    at C:\Users\hein_\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js:129:20
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickCallback (internal/process/next_tick.js:98:9)
    at Module.runMain (module.js:592:11)
    at run (bootstrap_node.js:394:7)

events.js:160
      throw er; // Unhandled 'error' event
      ^
Error: node_modules\node-sass\test\fixtures\depth-first\_vars.scss
Error: Undefined variable: "$import-counter".
        on line 1 of node_modules/node-sass/test/fixtures/depth-first/_vars.scss
>> $import_counter: $import_counter + 1;
   -----------------^

    at options.error (D:\Documenten\Howest\Semester 4\05 - Project\MarkeOnlinebis\Project Execution\MarkeOnline\node_modules\node-sass\lib\index.js:291:26)

Upvotes: 39

Views: 52369

Answers (4)

carloswm85
carloswm85

Reputation: 2396

You can use this solution for net5.0, net6.0, netcoreapp3.1, netstandard2.0

This example shows how to compile scss files from different sources into one single front-end css file.

What you'll use

INSTRUCTIONS

When creating a new ASP.NET Core MVC project, this is what you'll see in the frontend.

enter image description here

This is Bootstrap's 5.1.0 default theme, located at ~\wwwroot\lib\bootstrap\dist\css\bootstrap.css. We'll change this default theme using "Sass Compiler Library for .NET Core 3.1/5.x./6.x without node."

A. Download Bootstrap (example uses version 5.2.3)

  • Download missing Bootstrap files using libman.json

    1. Right-click on your project.

    2. Add, then Client-Side Library..., then in Library: search for the Bootstrap version you want, then Install.

      enter image description here

  • Default installation should:

    • Install all Bootstrap files under wwwroot folder, at lib folder.

    • We are interested in the content from scss folder.

      enter image description here

B. Install AspNetCore.SassCompiler

  • Using Nuget Package Manager tab:

    1. Right-click on project and select Manage NuGet Packages...
    2. Browse for the desired package and install it.
  • Using Nuget Package Manager or .NET CLI:

    # Package Manager
    PM> Install-Package AspNetCore.SassCompiler
    
    # .NET CLI
    dotnet add package AspNetCore.SassCompiler
    

C. Download Bootswatch files

https://bootswatch.com/

  • From their site, pick a theme (we'll pick Darkly):

    enter image description here

  • Download Darkly's Scss files into your project, at top level, inside a newly created folder named Styles:

    enter image description here

    Download both Scss files here:

    enter image description here

Note: Be aware that Bootswacth and Bootstrap must match same versions. I case they don't, go to Bootswatch's repository and navigate their branches and commits for getting what you need.

D. Compile ALL Scss files using AspNetCore.SassCompiler

You will add and modify the following files:

  • ~/Styles/site.scss
  • ~/Styles/_custom.scss
  • ~/appsettings.json
/* ~/Styles/site.scss */

// Bootswatch variables
@import "../Styles/_variables.scss";

// BOOTSTRAP
@import "../wwwroot/lib/bootstrap/scss/bootstrap.scss";

// Bootswatch
@import "../Styles/_bootswatch.scss";

// Project custom styling code goes here
@import "../Styles/_custom.scss";

The previous file will compile in runtime.

This is the configuration you'll need for AspNetCore.SassCompiler

/* ~/appsettings.json */
{
  // ...
  "SassCompiler": {
    "SourceFolder": "Styles",
    "TargetFolder": "wwwroot\\css",
    "Arguments": "--style=compressed",
    "GenerateScopedCss": true,
    "ScopedCssFolders": [ "Views", "Pages", "Shared", "Components" ],
    "IncludePaths": [],

    // You can override specific options based on the build configuration
    "Configurations": {
      "Debug": { // These options apply only to Debug builds
        "Arguments": "--style=expanded"
      }
    }
  }
  // ...
}

Result

  • From all of these files:

    • _variables.scss +
    • ../wwwroot/lib/bootstrap/scss/bootstrap.scss +
    • _bootswatch.scss +
    • _custom.scss
    • site.scss =
  • You will get:

    • ~\wwwroot\css\site.css
  • Changing default variables is made as mentioned in the code snippet.

  • Adding your own code is made the same way.

    enter image description here

Will result in:

enter image description here

(This is from a different project.)

  • You'll finally get something like:

    enter image description here

Also

You can add a watcher for runtime:

// startup.cs
public void ConfigureServices(IServiceCollection services) 
{
  
#if DEBUG
  services.AddSassCompiler();
#endif

}

Or:

// Program.cs
#if DEBUG
builder.Services.AddSassCompiler();
#endif

Upvotes: 6

live-love
live-love

Reputation: 52396

This is how you can add Sass to your Mvc app:

  • Download WebCompiler: https://marketplace.visualstudio.com/items?itemName=MadsKristensen.WebCompiler&ssr=false#qna
  • Double click on the Vsix file to install it.
  • Right click on solution, Manage Nuget Packages
  • Download bootstrap.sass package (version 4 or above)
  • Right click on the bootstrap.scss file under Content folder you need and select Web Compiler - Compile File
  • The bootstrap.css file will be generated.
  • You can select any scss file to compile.
  • You can see the configuration (list of files to be compiled) in the compilerconfig.json file in the root folder.
  • Add the css file to the bundle.

    bundles.Add(new StyleBundle("~/Content/css").Include(
              "~/Content/bootstrap/main.css",
              "~/Content/site.css"));
    

If you need to customize bootstrap, add a main.scss file in the same folder as bootstrap.scss. Then compile it using Web Compiler.

main.scss:

/* import the necessary Bootstrap files */
@import "_functions.scss";
@import "_variables.scss";

/* make changes to the !default Bootstrap variables */
$body-color: green;

/* finally, import Bootstrap to set the changes! */
@import "bootstrap.scss";

This example includes all the files, but make sure you only add the files you need to make the css smaller.

Upvotes: 10

haydar M.Al-samawe
haydar M.Al-samawe

Reputation: 291

You can use another way easier I think.

Step 1

Go with this steps in your NuGet Manager.

  1. Add Microsoft.AspNet.Web.Optimization

  2. Add BundleTransformer.SassAndScss

  3. Add LibSassHost.Native.win-x64 if you use system 64 bit.

  4. LibSassHost.Native.win-x86

Step2

In BundleConfig.cs add this code in RegisterBundles methode.

var nullBulider = new NullBuilder();
var nullOrderer = new NullOrderer();

BundleResolver.Current = new CustomBundleResolver();
var commonStyleBundle = new CustomStyleBundle("~/Bundle/sass");

commonStyleBundle.Include("~/css/main.scss");
commonStyleBundle.Orderer = nullOrderer;
bundles.Add(commonStyleBundle);

Step 3

Add CSS folder in your project and add main.scss file sheet inside.

Step 4

In your view, you need to use System.Web.Optimization.

@using System.Web.Optimization

And link your style sheet

@Styles.Render("~/Bundle/sass").

Step 5

In Global.asax we need to add this line in Application_Start().

RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);

Or maybe you will find it already in your class if you use MVC templet.

And that is it your main.scss its work.

Upvotes: 25

Ryan Holmes
Ryan Holmes

Reputation: 557

Try Web Compiler plugin instead this is what I use to compile SCSS in MVC.

A Visual Studio extension that compiles LESS, Sass, JSX, ES6 and CoffeeScript files.

Upvotes: 34

Related Questions