Contents

johnfairh/swift-sass

swift-sass

Examples

Minimally:

import DartSass

let compiler = try Compiler()

let results = try await compiler.compile(fileURL: scssFileURL)

print(results.css)

Although the compiler output is more structured, if this is all you want to do then you're probably better off running the binary directly. The reason to use this package is to provide custom implementations of @use rules to load content, and custom functions to provide application-specific behavior:


struct ExtrasImporter: Importer {
    func canonicalize(ruleURL: String, context: ImporterContext) async throws -> URL? {
      guard ruleURL == "extras" else {
      return nil
    }
    return URL(string: "custom://extras")
  }

  func load(canonicalURL: URL) async throws -> ImporterResults? {
    ImporterResults(my_extras_stylesheet)
  }
}

let customFunctions: SassFunctionMap = [
  "userColorForScore($score)" : { args in
    let score = try args[0].asInt()
    return SassColor(...)
  }
]

let results = try await compiler.compile(
    fileURL: scssFileURL,
    importers: [
      .loadPath(sassIncludeDirectoryFileURL),
      .importer(ExtrasImporter())
    ],
    functions: customFunctions
)
// stylesheet

@use "extras";

.score-mid {
  color: userColorForScore(50);
}

DartSass is built on NIO but the user interface is entirely Swift 5.5 async-await.

Documentation

Requirements

  • Swift 6.0
  • macOS 14+ (tested on macOS 26.x arm)
  • Linux (tested on Ubuntu latest IA)
  • Embedded Sass Protocol version 3.3.0

Installation

Only with Swift Package Manager, via Xcode or directly:

Package dependency:

.package(name: "swift-sass",
         url: "https://github.com/johnfairh/swift-sass.git",
         from: "3.4.0")

Target dependency:

.product(name: "DartSass", package: "swift-sass"),

The Swift package bundles the Dart Sass compiler for macOS and Linux (specifically Ubuntu Focal/20.04 64-bit) both x86_64 and arm64. The correct binary is selected at build time. The selection is made based on the host architecture though, so if you want to cross-compile you'll need to assemble the results manually.

For other platforms you will need to either download the correct version from the release page or build it manually, ship it as part of your program's distribution, and use this initializer.

There is no need to install a Dart runtime or SDK as part of this, the dart-sass-embedded program is standalone. The version required is shown in the VERSION_DART_SASS file.

On LibSass

LibSass is the C++ implementation of Sass. In recent years it has fallen behind the specification and reference implementations, and was deprecated in 2020.

Contributions

Welcome: open an issue / johnfairh@gmail.com / @johnfairh@mastodon.social

License

Distributed under the MIT license.

Package Metadata

Repository: johnfairh/swift-sass

Default branch: main

README: README.md