Compiling scss files in ASP.NET MVC action

2k views Asked by At

are any alternatives for compile .scss files in action in ASP.NET MVC controller?

I have /Content folder with two files: main.scss and external.scss. In my controller I'm using NSASS package:

    public ActionResult GetCss(string scssPath)
    {           
        string scss = @"@import """ + Server.MapPath(scssPath) + @""";";
        var compiler = new SassCompiler();
        string compiled = compiler.Compile(source: scss);             

        return Content(compiled.ToString(), "text/css");
    }

my view:

<link href="@Url.Action("GetCss", "Theme", new { scssPath="~/Content/sass/main.scss" })" rel="stylesheet" type="text/css" />

main.scss file:

@import "external";

I have error

Error: File to import not found or unreadable: external

I tried to write @import "external.scss" but same problem.

2

There are 2 answers

0
David Mikula On

NSass is outdated. It was updated last time in 2013 and can't compile many new scss syntaxes, but if you want to compile few simple lines and have rest precompiled, here's simplest solution I came up with.

string scss = System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + @"\Design\Scss\custom.scss");
scss += "$primary: #f80;$secondary: #0f2;";

Btw, if you would like to import other scss files into your main scss file, you can use following code but note I'm not good at Regex and thins it might have flaws.

scss = Regex.Replace(scss, "import \"", m=> m + AppDomain.CurrentDomain.BaseDirectory + @"Design\Scss\");
0
br1an On

We have the same (or similar problem). The problem I'm seeing is that SassCompiler is trying to find the @import files relative to the current working directory, instead of relative to the file which contains the @import.

There might be a few ways around this depending on what you're trying to do.

My workaround consisted of making a temporary copy of the directory structure and then updating all the @import statements in each file to make them relative to the working directory before compiling.


UPDATE I got this working without this hack by passing in all the paths to the 'includePaths' parameter. I had tried this before without success because I was using relative paths. If you use absolute paths then it works.