.NET wrapper around the LibSass library with the ability to support a virtual file system.
C++ C# C Batchfile CSS Makefile Other
Clone or download
Latest commit 4b5ee4f Apr 26, 2018

README.md

LibSass Host for .NET NuGet version Download count

LibSass Host logo

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

Installation

This library can be installed through NuGet. 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:

* - Requires api-ms-win-core-*.dll, api-ms-win-crt-*.dll, concrt140.dll, msvcp140.dll, ucrtbase.dll and vcruntime140.dll assemblies from the Microsoft Visual C++ 2015 Redistributable.

If you need support for other operating systems, then you should read the “Building LibSass” section.

Mono support

LibSassHost.Native.linux-x64 and LibSassHost.Native.osx-x64 packages do not support installation under Mono, 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 from the LibSass Host's project repository.
  2. Extract a assembly file from the LibSassHost.Native.linux-x64 package. The libsass.so file is located in the runtimes/linux-x64/native/ directory of NuGet package.
  3. Build a assembly file 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 from the LibSass Host's project repository.
  2. Extract a assembly file from the LibSassHost.Native.osx-x64 package. The libsass.dylib file is located in the runtimes/osx-x64/native/ directory of NuGet package.
  3. Build a assembly file 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, SharpScss, NSass, Sass.Net) is ability to support a virtual file system. You can set the file manager by using FileManager property of the SassCompiler class:

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:

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:

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 (SassСompilationException e)
			{
				Console.WriteLine("During compilation of SCSS code an error occurred. See details:");
				Console.WriteLine();
				Console.WriteLine(SassErrorHelpers.Format(e));
			}
		}
	}
}

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

  1. content - text content written on Sass/SCSS.
  2. inputPath - path to input Sass/SCSS file. Needed for generation of source map.
  3. 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.
  4. 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.
  5. options (optional) - compilation options (instance of the CompilationOptions class)

Then output result of compilation to the console. In addition, we provide handling of the SassСompilationException 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:

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 (SassСompilationException e)
			{
				Console.WriteLine("During compilation of SCSS file an error occurred. See details:");
				Console.WriteLine();
				Console.WriteLine(SassErrorHelpers.Format(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 2013, 2015 or 2017 with C++ support.

To build the LibSass on Windows:

  1. Open libsass.sln in Visual Studio.
  2. Select the Configuration and target Platform, and build the solution.
  3. 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: