Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 39 ยท Tooling and Build

The Sass JavaScript API

Use Sass from Node and the browser: compile, compileString, options, custom functions, custom importers, loggers and source maps, plus the removed legacy render API.

The command line is enough for simple builds, but tools such as bundlers, static site generators and online playgrounds call Sass from JavaScript. The JavaScript API is also how you extend Sass: you can write functions in JavaScript that stylesheets call, or teach the compiler to load files from a database or memory instead of the disk. The code editors in this tutorial use exactly this API.

All the examples use the modern API (compile, compileString). The older render() and renderSync() ("legacy API") are deprecated and scheduled for removal in Sass 2.0, so do not use them in new code.

Compiling

JavaScript
import * as sass from "sass";

// From a file on disk (Node only)
const result = sass.compile("src/main.scss", { style: "compressed" });

// From a string (Node and browser)
const result2 = sass.compileString("a { b: 1 + 2 }");

console.log(result.css);          // the compiled CSS text
console.log(result.loadedUrls);   // every file that was read (an array of URL objects)
console.log(result.sourceMap);    // only if sourceMap: true was passed

Both functions are synchronous. There are compileAsync and compileStringAsync variants that return promises and are required when an importer or function is asynchronous. In Node, the async versions with sass-embedded use worker processes so many builds run in parallel.

Errors throw an Exception object with useful fields:

JavaScript
try {
  sass.compileString("a { b: 1px + 1s }");
} catch (e) {
  console.log(e.sassMessage);   // "1px and 1s have incompatible units."
  console.log(e.span.start);    // { offset, line, column } (0-based)
  console.log(e.sassStack);     // the "stack trace" in Sass terms
}

Common options

Option Meaning
style "expanded" (default) or "compressed"
sourceMap true to return a source map object in result.sourceMap
loadPaths Array of folders to search for @use (Node)
importers Custom importers (see below)
functions Custom functions written in JavaScript
logger Receive @debug and @warn messages and deprecations
quietDeps Hide warnings from files found via load paths
silenceDeprecations, fatalDeprecations Deprecation ids to ignore or turn into errors
charset false to stop adding @charset / BOM
syntax (compileString only) "scss" (default), "indented" or "css"
url (compileString) The URL of the string, so relative @use and error messages work

Custom functions

Functions are given as an object whose keys are Sass signatures and whose values are JavaScript functions. The function receives an array of Sass values and must return a Sass value.

JavaScript
sass.compileString(source, {
  functions: {
    "to-rem($px)": (args) => {
      const px = args[0].assertNumber("px").value;
      return new sass.SassNumber(px / 16, "rem");
    },
    "env-name()": () => new sass.SassString("production", { quotes: false }),
  },
});

The classes mirror Sass's types: SassNumber, SassString, SassColor, SassList, SassMap, SassBoolean (use the constants sass.sassTrue and sass.sassFalse) and sass.sassNull. Values have assert... helpers (assertNumber, assertString, assertMap) that throw a helpful Sass error with the argument name if the type is wrong.

Do not name a custom function after a built-in CSS math function (rem, min, max, round, mod, abs, clamp, calc). Sass treats those as calculations and will not call your JavaScript. That is why the example is to-rem, not rem.

Custom functions are how you read design data from JSON, compute a hash for cache busting, or call a database at build time. Keep them pure and fast; a slow function is called every time a stylesheet uses it.

Capturing messages with a logger

JavaScript
const messages = [];
sass.compileString('@debug "hello"; @warn "careful";', {
  logger: {
    debug: (message, options) => messages.push(`debug (line ${options.span.start.line + 1}): ${message}`),
    warn: (message, options) => messages.push(`warn: ${message}${options.deprecation ? " [deprecation]" : ""}`),
  },
});

Passing sass.Logger.silent ignores everything. Build tools use the logger to show Sass messages in their own format.

Custom importers

An importer teaches Sass how to resolve and load a URL. It has two methods:

  • canonicalize(url, context) returns an absolute URL object that uniquely names the file, or null if this importer does not handle that URL.
  • load(canonicalUrl) returns { contents, syntax } for the canonical URL.
JavaScript
const files = { "tokens": "$brand: #4f46e5;" };

const memoryImporter = {
  canonicalize: (url) => (url.startsWith("mem:") ? new URL(url) : null),
  load: (canonicalUrl) => ({ contents: files[canonicalUrl.pathname], syntax: "scss" }),
};

sass.compileString('@use "mem:tokens"; a { color: tokens.$brand }', { importers: [memoryImporter] });

This is exactly what the playgrounds on this site do for the mem: editors. The same pattern can load from a virtual file system, a bundler's in-memory cache or a package registry. For file-based projects, Sass ships NodePackageImporter (Node only), which resolves URLs starting with pkg::

JavaScript
import { NodePackageImporter } from "sass";
sass.compile("main.scss", { importers: [new NodePackageImporter()] });
// then in Sass: @use "pkg:bootstrap/scss/variables";

It reads each package's package.json sass or exports field, so you need no ~ prefix or relative node_modules path.

A live example

Custom function, importer and logger

Change 32px to 20px and watch the rem value. Remove the @use line and see loadedUrls become empty.

Using the API in a Node build script

JavaScript
import * as sass from "sass";
import { readFileSync, writeFileSync, mkdirSync } from "node:fs";

mkdirSync("dist", { recursive: true });
const { css, sourceMap } = sass.compile("src/main.scss", {
  style: "compressed",
  sourceMap: true,
  loadPaths: ["node_modules"],
  quietDeps: true,
});

writeFileSync("dist/main.css", css + "\n/*# sourceMappingURL=main.css.map */");
writeFileSync("dist/main.css.map", JSON.stringify(sourceMap));

The map object has sources, mappings and so on, ready to write as JSON. When no sourceMappingURL comment is added, browsers do not look for the map.

sass versus sass-embedded in code

Both packages expose the same API. Swap the import and nothing else changes:

JavaScript
import * as sass from "sass-embedded";

sass-embedded starts a native compiler process and is much faster on big builds, particularly with compileAsync. Remember to call await sass.initAsyncCompiler() and dispose of the compiler when you compile repeatedly in a long-running process.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which function compiles Sass source held in a JavaScript string?

    compile reads a path from disk; compileString takes the source text itself.
  2. 2. In the functions option, what is the key?

    The key declares the Sass signature; the value is the JavaScript implementation.
  3. 3. What must a custom importer's canonicalize method return?

    canonicalize names the file uniquely; load then provides the contents.
  4. 4. Why not name a custom function rem?

    Names such as min, max, round and rem are reserved for CSS math functions.
  5. 5. Which API is deprecated and should not be used in new code?

    The legacy API will be removed in Sass 2.0; use compile and compileString.

Summary

  • compile(path) and compileString(source) return { css, loadedUrls, sourceMap }; async variants return promises.
  • Options include style, sourceMap, loadPaths, importers, functions, logger, quietDeps and deprecation settings.
  • Custom functions use Sass signatures as keys and the Sass* value classes for arguments and results.
  • Custom importers implement canonicalize and load; NodePackageImporter handles pkg: URLs.
  • A logger captures @debug and @warn; use sass-embedded for speed and avoid the legacy render API.

Next: Bundlers, PostCSS and Frameworks