Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/Taritsyn/LibSassHost

.NET wrapper around the LibSass library with the ability to support a virtual file system.
https://github.com/Taritsyn/LibSassHost

css dotnet libsass sass scss

Last synced: about 1 month ago
JSON representation

.NET wrapper around the LibSass library with the ability to support a virtual file system.

Awesome Lists containing this project

README

        

LibSass Host for .NET [![NuGet version](https://img.shields.io/nuget/v/LibSassHost.svg)](https://www.nuget.org/packages/LibSassHost/) [![Download count](https://img.shields.io/nuget/dt/LibSassHost.svg)](https://www.nuget.org/packages/LibSassHost/)
=====================

LibSass Host logo

.NET wrapper around the [LibSass](https://github.com/sass/libsass) library with the ability to support a virtual file system.

## Installation
This library can be installed through NuGet.
[LibSassHost](https://www.nuget.org/packages/LibSassHost/) package does not contain the native implementations of the LibSass.
Therefore, you need to choose and install the most appropriate package(s) for your platform.
The following packages are available:

* [LibSassHost.Native.win-x86](https://www.nuget.org/packages/LibSassHost.Native.win-x86/) contains the native assembly for Windows (x86).
* [LibSassHost.Native.win-x64](https://www.nuget.org/packages/LibSassHost.Native.win-x64/) contains the native assembly for Windows (x64).
* [LibSassHost.Native.win-arm](https://www.nuget.org/packages/LibSassHost.Native.win-arm/) contains the native assembly for Windows (ARM).
* [LibSassHost.Native.win-arm64](https://www.nuget.org/packages/LibSassHost.Native.win-arm64/) contains the native assembly for Windows (ARM64).
* [LibSassHost.Native.linux-x64](https://www.nuget.org/packages/LibSassHost.Native.linux-x64/) contains the native assembly for Linux (x64). Only compatible with .NET Core.
* [LibSassHost.Native.osx-x64](https://www.nuget.org/packages/LibSassHost.Native.osx-x64/) contains the native assembly for OS X (x64). Only compatible with .NET Core.

If you need support for other operating systems, then you should read the [“Building LibSass”](#building-libsass) section.

### Mono support

LibSassHost.Native.linux-x64 and LibSassHost.Native.osx-x64 packages do not support installation under [Mono](http://www.mono-project.com/), but you can to install the native assemblies manually.

#### Linux

First you need to get the `libsass.so` assembly file. You have 3 ways to do this:

1. [Download a assembly file](https://github.com/Taritsyn/LibSassHost/blob/master/lib/linux-x64/libsass.so) from the LibSass Host's project repository.
1. Extract a assembly file from the [LibSassHost.Native.linux-x64](https://www.nuget.org/packages/LibSassHost.Native.linux-x64/) package. The `libsass.so` file is located in the `runtimes/linux-x64/native/` directory of NuGet package.
1. [Build a assembly file](#building-libsass) from the source code.

Afterwards open a terminal window and change directory to the directory where the `libsass.so` file is located. Next, enter the following command:

```
sudo cp libsass.so /usr/local/lib/
sudo ldconfig
```

#### OS X

First you need to get the `libsass.dylib` assembly file. You have 3 ways to do this:

1. [Download a assembly file](https://github.com/Taritsyn/LibSassHost/blob/master/lib/osx-x64/libsass.dylib) from the LibSass Host's project repository.
1. Extract a assembly file from the [LibSassHost.Native.osx-x64](https://www.nuget.org/packages/LibSassHost.Native.osx-x64/) package. The `libsass.dylib` file is located in the `runtimes/osx-x64/native/` directory of NuGet package.
1. [Build a assembly file](#building-libsass) from the source code.

Afterwards open a terminal window and change directory to the directory where the `libsass.dylib` file is located. Next, enter the following command:

```
mkdir -p /usr/local/lib/ && cp libsass.dylib "$_"
```

## Usage
The main difference between this library from other .NET wrappers around the LibSass (e.g. [libsassnet](https://github.com/darrenkopp/libsass-net/), [SharpScss](https://github.com/xoofx/SharpScss), [NSass](https://github.com/TBAPI-0KA/NSass), [Sass.Net](https://www.nuget.org/packages/XWeb.Web.Sass.Core)) is ability to support a virtual file system. You can set the file manager by using `FileManager` property of the SassCompiler class:

```csharp
SassCompiler.FileManager = CustomFileManager();
```

Any class, that implements an IFileManager interface, can be used as a file manager.
By default, file manager is not specified, and for access to the file system are used built-in tools of the LibSass library.
The main advantage of using built-in tools is the low memory consumption.
But there is a disadvantage: there is no ability to process files in UTF-16 encoding.

To resolve this disadvantage you need to use the FileManager class:

```csharp
SassCompiler.FileManager = FileManager.Instance;
```

But in this case, will increase memory consumption (approximately 3 times).

A good example of implementing a custom file manager, which provides access to the virtual file system, is the VirtualFileManager class from the BundleTransformer.SassAndScss package.

It should also be noted, that this library does not write the result of compilation to disk. `Compile` and `CompileFile` methods of the SassCompiler class return the result of compilation in the form of an instance of the CompilationResult class. Consider in detail properties of the CompilationResult class:



Property name
Data type
Description




CompiledContent
String
CSS code.


IncludedFilePaths
IList<string>
List of included files.


SourceMap
String
Source map.

Consider a simple example of usage of the `Compile` method:

```csharp
using System;

using LibSassHost;
using LibSassHost.Helpers;

namespace LibSassHost.Example.ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
const string inputContent = @"$font-stack: Helvetica, sans-serif;
$primary-color: #333;

body {
font: 100% $font-stack;
color: $primary-color;
}";

try
{
var options = new CompilationOptions { SourceMap = true };
CompilationResult result = SassCompiler.Compile(inputContent, "input.scss", "output.css",
"output.css.map", options);

Console.WriteLine("Compiled content:{1}{1}{0}{1}", result.CompiledContent,
Environment.NewLine);
Console.WriteLine("Source map:{1}{1}{0}{1}", result.SourceMap, Environment.NewLine);
Console.WriteLine("Included file paths: {0}",
string.Join(", ", result.IncludedFilePaths));
}
catch (SassCompilationException e)
{
Console.WriteLine("During compilation of SCSS code an error occurred. See details:");
Console.WriteLine();
Console.WriteLine(SassErrorHelpers.GenerateErrorDetails(e));
}
}
}
}
```

First we call the `Compile` method of SassCompiler class with the following parameters:

1. `content` - text content written on Sass/SCSS.
1. `inputPath` - path to input Sass/SCSS file. Needed for generation of source map.
1. `outputPath` (optional) - path to output CSS file. Needed for generation of source map. If path to output file is not specified, but specified a path to input file, then value of this parameter is obtained by replacing extension in the input file path by `.css` extension.
1. `sourceMapPath` (optional) - path to source map file. If path to source map file is not specified, but specified a path to output file, then value of this parameter is obtained by replacing extension in the output file path by `.css.map` extension.
1. `options` (optional) - compilation options (instance of the CompilationOptions class)

Then output result of compilation to the console. In addition, we provide handling of the SassCompilationException exception.

And now let's consider in detail properties of the CompilationOptions class:



Property name
Data type
Default value
Description




AdditionalImportExtensions
IList<string>
.css
List of additional @import file extensions.


IncludePaths
IList<string>
Empty list
List of include paths.


IndentType
IndentType enumeration
Space
Indent type. Can take the following values:



  • Space - space character


  • Tab - tab character





IndentWidth
Int32
2
Number of spaces or tabs to be used for indentation.


InlineSourceMap
Boolean
false
Flag for whether to embed sourceMappingUrl as data uri.


LineFeedType
LineFeedType enumeration
Lf
Line feed type. Can take the following values:


  • Cr - Macintosh (CR)


  • CrLf - Windows (CR LF)


  • Lf - Unix (LF)

  • LfCr





OmitSourceMapUrl
Boolean
false
Flag for whether to disable sourceMappingUrl in css output.


OutputStyle
OutputStyle enumeration
Nested
Output style for the generated css code. Can take the following values:

  • Nested

  • Expanded

  • Compact

  • Compressed





Precision
Int32
5
Precision for fractional numbers.


SourceComments
Boolean
false
Flag for whether to emit comments in the generated CSS indicating the corresponding source line.


SourceMap
Boolean
false
Flag for whether to enable source map generation.


SourceMapFileUrls
Boolean
false
Flag for whether to create file urls for sources.


SourceMapIncludeContents
Boolean
false
Flag for whether to include contents in maps.


SourceMapRootPath
String
Empty string
Value will be emitted as sourceRoot in the source map information.

Using of the `CompileFile` method quite a bit different from using of the `Compile` method:

```csharp
using System;
using System.IO;

using LibSassHost;
using LibSassHost.Helpers;

namespace LibSassHost.Example.ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
const string basePath = "/Projects/TestSass";
string inputFilePath = Path.Combine(basePath, "style.scss");
string outputFilePath = Path.Combine(basePath, "style.css");
string sourceMapFilePath = Path.Combine(basePath, "style.css.map");

try
{
var options = new CompilationOptions { SourceMap = true };
CompilationResult result = SassCompiler.CompileFile(inputFilePath, outputFilePath,
sourceMapFilePath, options);

Console.WriteLine("Compiled content:{1}{1}{0}{1}", result.CompiledContent,
Environment.NewLine);
Console.WriteLine("Source map:{1}{1}{0}{1}", result.SourceMap, Environment.NewLine);
Console.WriteLine("Included file paths: {0}",
string.Join(", ", result.IncludedFilePaths));
}
catch (SassCompilationException e)
{
Console.WriteLine("During compilation of SCSS file an error occurred. See details:");
Console.WriteLine();
Console.WriteLine(SassErrorHelpers.GenerateErrorDetails(e));
}
}
}
}
```

In this case, the `inputPath` parameter is used instead of the `content` parameter. Moreover, value of the `inputPath` parameter now should contain the path to real file.

## Building LibSass
LibSassHost uses a modified version of the LibSass library.
In most cases, you do not need to build the LibSass from source code, because the native assemblies is published as `LibSassHost.Native.*` NuGet packages.
The only exception is the case, when you want to build library for a specific Linux distro.

To build a modified version of the LibSass you must first clone the LibSassHost repository:

```
mkdir Github && cd Github
git clone https://github.com/Taritsyn/LibSassHost.git
```

Further actions depend on your operating system.

### Windows
In your system must be installed Visual Studio 2019 or 2022 with C++ support.

To build the LibSass on Windows:

1. Open `libsass.sln` in Visual Studio.
1. Select the **Configuration** and target **Platform**, and build the solution.
1. Build output will be under `src\libsass\bin\[Debug|Release]\[Win32|x64]`.

Alternatively, you can use the build script.
Open a Visual Studio developer command prompt and run the `build-libsass.cmd` script from your `LibSassHost` project directory:

```
C:\Users\username\Github\LibSassHost> build-libsass
```

Build script can also take a options, information about which can be obtained by using the following command:

```
build-libsass /?
```

### Linux
In your system must be installed GCC (GNU Compiler Collection).
In every Linux distro installation of GCC is made in different ways.
For example, in Ubuntu 16.04 this is done as follows:

```
sudo apt-get update
sudo apt-get install build-essential
```

To build the LibSass on Linux open a terminal window and run the `build-libsass.sh` script from your `LibSassHost` project directory:

```
username@ubuntu-16:~/Github/LibSassHost$ ./build-libsass.sh
```

Build output will be under `src/libsass/bin/[Debug|Release]/Linux`.

Build script can also take a options, information about which can be obtained by using the following command:

```
./build-libsass.sh --help
```

### OS X
In your system must be installed Xcode Command Line Tools.
To install Xcode Command Line Tools, in your terminal simply run:

```
xcode-select --install
```

To build the LibSass on OS X open a terminal window and run the `build-libsass.sh` script from your `LibSassHost` project directory:

```
My-Mac:LibSassHost username$ ./build-libsass.sh
```

Build output will be under `src/libsass/bin/[Debug|Release]/OSX`.

Build script can also take a options, information about which can be obtained by using the following command:

```
./build-libsass.sh --help
```

## Who's Using LibSass Host for .NET
If you use the LibSass Host for .NET in some project, please send me a message so I can include it in this list:

* [Abstractions.Sass.CrossPlatformLibSass](https://www.nuget.org/packages/Abstractions.Sass.CrossPlatformLibSass)
* [Core Sass Compiler](https://github.com/benwmills/core-sass-compiler) by Ben Mills
* [CssBuilder](https://github.com/x-projs/CssBuilder)
* [JacobDixon.AspNetCore.LiveSassCompile](https://github.com/JakeDixon/JacobDixon.AspNetCore.LiveSassCompile) by Jacob Dixon
* [Karambolo.AspNetCore.Bundling](https://github.com/adams85/bundling) by Adam Simon
* [LibSassBuilder](https://github.com/johan-v-r/LibSassBuilder) by Johan van Rensburg
* [MustardBlack-Core.Assets.Css.Sass](https://www.nuget.org/packages/MustardBlack-Core.Assets.Css.Sass/) by Andrew Bullock
* [Profound.Kentico.SassPlugin](https://www.nuget.org/packages/Profound.Kentico.SassPlugin/) by Arindam Debnath
* [Sass.AspNetCore](https://www.nuget.org/packages/Sass.AspNetCore/) by Aleksandr Ovchinnikov
* [VirtoCommerce Storefront for ASP.NET Core](https://github.com/VirtoCommerce/vc-storefront-core) by Virto Solutions LTD