sass
- Version 1.81.1
- Published
- 5.66 MB
- 3 dependencies
- MIT license
Install
npm i sass
yarn add sass
pnpm add sass
Overview
A pure JavaScript implementation of Sass.
Index
Variables
Functions
Classes
Interfaces
Deprecations
- 'abs-percent'
- 'bogus-combinators'
- 'call-string'
- 'color-4-api'
- 'color-functions'
- 'color-module-compat'
- 'css-function-mixin'
- 'duplicate-var-flags'
- 'feature-exists'
- 'fs-importer-cwd'
- 'function-units'
- 'global-builtin'
- 'legacy-js-api'
- 'mixed-decls'
- 'moz-document'
- 'new-global'
- 'null-alpha'
- 'relative-canonical'
- 'slash-div'
- 'strict-unary'
- 'user-authored'
- elseif
- import
Type Aliases
- CalculationOperator
- CalculationValue
- ChannelName
- ChannelNameHsl
- ChannelNameHwb
- ChannelNameLab
- ChannelNameLch
- ChannelNameRgb
- ChannelNameXyz
- ColorSpaceHsl
- ColorSpaceHwb
- ColorSpaceLab
- ColorSpaceLch
- ColorSpaceRgb
- ColorSpaceXyz
- CustomFunction
- DeprecationOrId
- DeprecationStatus
- GamutMapMethod
- HueInterpolationMethod
- KnownColorSpace
- LegacyAsyncFunction
- LegacyAsyncFunctionDone
- LegacyAsyncImporter
- LegacyFunction
- LegacyImporter
- LegacyImporterResult
- LegacyOptions
- LegacySyncFunction
- LegacySyncImporter
- LegacyValue
- ListSeparator
- LoggerWarnOptions
- OutputStyle
- PolarColorSpace
- PromiseOr
- RectangularColorSpace
- StringOptionsWithImporter
- StringOptionsWithoutImporter
- Syntax
Namespaces
Variables
variable deprecations
const deprecations: Deprecations;
An object containing all deprecation types.
Messages dart: "1.74.0", node: false
variable FALSE
const FALSE: types.Boolean<false>;
A shorthand for
sass.types.Boolean.FALSE
.Legacy
Deprecated
This only works with the legacy render and renderSync APIs. Use sassFalse with compile, compileString, compileAsync, and compileStringAsync instead.
variable info
const info: string;
Information about the Sass implementation. This always begins with a unique identifier for the Sass implementation, followed by U+0009 TAB, followed by its npm package version. Some implementations include additional information as well, but not in any standardized format.
* For Dart Sass, the implementation name is
dart-sass
. * For Node Sass, the implementation name isnode-sass
. * For the embedded host, the implementation name issass-embedded
.
variable NULL
const NULL: types.Null;
A shorthand for
sass.types.Null.NULL
.Legacy
Deprecated
This only works with the legacy render and renderSync APIs. Use sassNull with compile, compileString, compileAsync, and compileStringAsync instead.
variable sassFalse
const sassFalse: SassBoolean;
Sass's [
false
value](https://sass-lang.com/documentation/values/booleans).Custom Function
variable sassNull
const sassNull: Value;
Sass's [
null
value](https://sass-lang.com/documentation/values/null).Custom Function
variable sassTrue
const sassTrue: SassBoolean;
Sass's [
true
value](https://sass-lang.com/documentation/values/booleans).Custom Function
variable TRUE
const TRUE: types.Boolean<true>;
A shorthand for
sass.types.Boolean.TRUE
.Legacy
Deprecated
This only works with the legacy render and renderSync APIs. Use sassTrue with compile, compileString, compileAsync, and compileStringAsync instead.
Functions
function compile
compile: (path: string, options?: Options<'sync'>) => CompileResult;
Synchronously compiles the Sass file at
path
to CSS. If it succeeds it returns a CompileResult, and if it fails it throws an Exception.This only allows synchronous Importers and CustomFunctions.
**Heads up!** When using the [sass-embedded] npm package for single compilations, **compileAsync is almost always faster than compile**, due to the overhead of emulating synchronous messaging with worker threads and concurrent compilations being blocked on main thread.
If you are running multiple compilations with the [sass-embedded] npm package, using a Compiler will provide some speed improvements over the module-level methods, and an AsyncCompiler will be much faster.
[sass-embedded]: https://www.npmjs.com/package/sass-embedded
Example 1
const sass = require('sass');const result = sass.compile("style.scss");console.log(result.css);Compile dart: "1.45.0", node: false
function compileAsync
compileAsync: ( path: string, options?: Options<'async'>) => Promise<CompileResult>;
Asynchronously compiles the Sass file at
path
to CSS. Returns a promise that resolves with a CompileResult if it succeeds and rejects with an Exception if it fails.This only allows synchronous or asynchronous Importers and CustomFunctions.
**Heads up!** When using the
sass
npm package, **compile is almost twice as fast as compileAsync**, due to the overhead of making the entire evaluation process asynchronous.Example 1
const sass = require('sass');const result = await sass.compileAsync("style.scss");console.log(result.css);Compile dart: "1.45.0", node: false
function compileString
compileString: ( source: string, options?: StringOptions<'sync'>) => CompileResult;
Synchronously compiles a stylesheet whose contents is
source
to CSS. If it succeeds it returns a CompileResult, and if it fails it throws an Exception.This only allows synchronous Importers and CustomFunctions.
**Heads up!** When using the [sass-embedded] npm package for single compilations, **compileStringAsync is almost always faster than compileString**, due to the overhead of emulating synchronous messaging with worker threads and concurrent compilations being blocked on main thread.
If you are running multiple compilations with the [sass-embedded] npm package, using a Compiler will provide some speed improvements over the module-level methods, and an AsyncCompiler will be much faster.
[sass-embedded]: https://www.npmjs.com/package/sass-embedded
Example 1
const sass = require('sass');const result = sass.compileString(`h1 {font-size: 40px;code {font-face: Roboto Mono;}}`);console.log(result.css);Compile dart: "1.45.0", node: false
function compileStringAsync
compileStringAsync: ( source: string, options?: StringOptions<'async'>) => Promise<CompileResult>;
Asynchronously compiles a stylesheet whose contents is
source
to CSS. Returns a promise that resolves with a CompileResult if it succeeds and rejects with an Exception if it fails.This only allows synchronous or asynchronous Importers and CustomFunctions.
**Heads up!** When using the
sass
npm package, **compileString is almost twice as fast as compileStringAsync**, due to the overhead of making the entire evaluation process asynchronous.Example 1
const sass = require('sass');const result = await sass.compileStringAsync(`h1 {font-size: 40px;code {font-face: Roboto Mono;}}`);console.log(result.css);Compile dart: "1.45.0", node: false
function initAsyncCompiler
initAsyncCompiler: () => Promise<AsyncCompiler>;
Creates an asynchronous AsyncCompiler. Each compiler instance exposes the compileAsync and compileStringAsync methods within the lifespan of the Compiler. Given identical input, these methods will return results identical to their counterparts exposed at the module root. To use synchronous compilation, use initCompiler;
When calling the compile functions multiple times, using a compiler instance with the [sass-embedded] npm package is much faster than using the top-level compilation methods or the [sass] npm package.
[sass-embedded]: https://www.npmjs.com/package/sass-embedded
[sass]: https://www.npmjs.com/package/sass
Example 1
const sass = require('sass');async function setup() {const compiler = await sass.initAsyncCompiler();const result1 = await compiler.compileStringAsync('a {b: c}').css;const result2 = await compiler.compileStringAsync('a {b: c}').css;await compiler.dispose();// throws errorconst result3 = await sass.compileStringAsync('a {b: c}').css;}Compile dart: "1.70.0", node: false
function initCompiler
initCompiler: () => Compiler;
Creates a synchronous Compiler. Each compiler instance exposes the compile and compileString methods within the lifespan of the Compiler. Given identical input, these methods will return results identical to their counterparts exposed at the module root. To use asynchronous compilation, use initAsyncCompiler.
When calling the compile functions multiple times, using a compiler instance with the [sass-embedded] npm package is much faster than using the top-level compilation methods or the [sass] npm package.
[sass-embedded]: https://www.npmjs.com/package/sass-embedded
[sass]: https://www.npmjs.com/package/sass
Example 1
const sass = require('sass');function setup() {const compiler = sass.initCompiler();const result1 = compiler.compileString('a {b: c}').css;const result2 = compiler.compileString('a {b: c}').css;compiler.dispose();// throws errorconst result3 = sass.compileString('a {b: c}').css;}Compile dart: "1.70.0", node: false
function render
render: ( options: LegacyOptions<'async'>, callback: (exception?: LegacyException, result?: LegacyResult) => void) => void;
This function asynchronously compiles a Sass file to CSS, and calls
callback
with a LegacyResult if compilation succeeds or LegacyException if it fails.**Heads up!** When using the
sass
npm package, **renderSync is almost twice as fast as render** by default, due to the overhead of making the entire evaluation process asynchronous.const sass = require('sass'); // or require('node-sass');sass.render({file: "style.scss"}, function(err, result) {// ...});Legacy
Deprecated
Use compileAsync or compileStringAsync instead.
function renderSync
renderSync: (options: LegacyOptions<'sync'>) => LegacyResult;
This function synchronously compiles a Sass file to CSS. If it succeeds, it returns the result, and if it fails it throws an error.
**Heads up!** When using the
sass-embedded
npm package, **render is almost always faster than renderSync**, due to the overhead of emulating synchronous messaging with worker threads and concurrent compilations being blocked on main thread.Example 1
const sass = require('sass'); // or require('node-sass');const result = sass.renderSync({file: "style.scss"});// ...Legacy
Deprecated
Use compile or compileString instead.
Classes
class AsyncCompiler
class AsyncCompiler {}
The result of creating an asynchronous compiler. Returned by initAsyncCompiler.
Compile
method compileAsync
compileAsync: ( path: string, options?: Options<'async'>) => Promise<CompileResult>;
The compileAsync method exposed through an Async Compiler instance while it is active. If this is called after dispose on the Async Compiler instance, an error will be thrown.
During the Async Compiler instance's lifespan, given the same input, this will return an identical result to the compileAsync method exposed at the module root.
method compileStringAsync
compileStringAsync: ( source: string, options?: StringOptions<'async'>) => Promise<CompileResult>;
The compileStringAsync method exposed through an Async Compiler instance while it is active. If this is called after dispose on the Async Compiler instance, an error will be thrown.
During the Async Compiler instance's lifespan, given the same input, this will return an identical result to the compileStringAsync method exposed at the module root.
method dispose
dispose: () => Promise<void>;
Ends the lifespan of this Async Compiler instance. After this is invoked, all subsequent calls to the Compiler instance's
compileAsync
orcompileStringAsync
methods will result in an error.Any compilations that are submitted before
dispose
will not be cancelled, and will be allowed to settle.After all compilations have been settled and Sass completes any internal task cleanup,
dispose
will resolve its promise.
class CalculationInterpolation
class CalculationInterpolation implements ValueObject {}
A string injected into a SassCalculation using interpolation. Unlike unquoted strings, interpolations are always surrounded in parentheses when they appear in CalculationOperations. Custom Function
constructor
constructor(value: string);
Creates a Sass CalculationInterpolation with the given
value
.
property value
readonly value: string;
Returns the interpolation's
value
field.
method equals
equals: (other: unknown) => boolean;
method hashCode
hashCode: () => number;
class CalculationOperation
class CalculationOperation implements ValueObject {}
A binary operation that can appear in a SassCalculation. Custom Function
constructor
constructor( operator: CalculationOperator, left: CalculationValue, right: CalculationValue);
Creates a Sass CalculationOperation with the given
operator
,left
, andright
values.Throws
Error
ifleft
orright
are quoted SassStrings.
property left
readonly left: CalculationValue;
Returns the operation's
left
field.
property operator
readonly operator: CalculationOperator;
Returns the operation's
operator
field.
property right
readonly right: CalculationValue;
Returns the operation's
right
field.
method equals
equals: (other: unknown) => boolean;
method hashCode
hashCode: () => number;
class Compiler
class Compiler {}
The result of creating a synchronous compiler. Returned by initCompiler.
Compile
method compile
compile: (path: string, options?: Options<'sync'>) => CompileResult;
The compile method exposed through a Compiler instance while it is active. If this is called after dispose on the Compiler instance, an error will be thrown.
During the Compiler instance's lifespan, given the same input, this will return an identical result to the compile method exposed at the module root.
method compileString
compileString: ( source: string, options?: StringOptions<'sync'>) => CompileResult;
The compileString method exposed through a Compiler instance while it is active. If this is called after dispose on the Compiler instance, an error will be thrown.
During the Compiler instance's lifespan, given the same input, this will return an identical result to the compileString method exposed at the module root.
method dispose
dispose: () => void;
Ends the lifespan of this Compiler instance. After this is invoked, all calls to the Compiler instance's compile or compileString methods will result in an error.
class Exception
class Exception extends Error {}
An exception thrown because a Sass compilation failed.
Other
property message
message: string;
A human-friendly representation of the exception.
Because many tools simply print
Error.message
directly, this includes not only the textual description of what went wrong (the sassMessage) but also an indication of where in the Sass stylesheet the error occurred (the span) and the Sass stack trace at the point of error (the sassStack).
property sassMessage
readonly sassMessage: string;
property sassStack
readonly sassStack: string;
A human-friendly representation of the Sass stack trace at the point of error.
property span
readonly span: SourceSpan;
The location the error occurred in the Sass file that triggered it.
method toString
toString: () => string;
Returns the same string as message.
class NodePackageImporter
class NodePackageImporter {}
The built-in Node.js package importer. This loads pkg: URLs from node_modules according to the standard Node.js resolution algorithm.
A Node.js package importer is exposed as a class that can be added to the
importers
option.const sass = require('sass');sass.compileString('@use "pkg:vuetify', {importers: [new sass.NodePackageImporter()]});## Writing Sass packages
Package authors can control what is exposed to their users through their
package.json
manifest. The recommended method is to add asass
conditional export topackage.json
.// node_modules/uicomponents/package.json{"exports": {".": {"sass": "./src/scss/index.scss","import": "./dist/js/index.mjs","default": "./dist/js/index.js"}}}This allows a package user to write
@use "pkg:uicomponents"
to load the file atnode_modules/uicomponents/src/scss/index.scss
.The Node.js package importer supports the variety of formats supported by Node.js [package entry points], allowing authors to expose multiple subpaths.
[package entry points]: https://nodejs.org/api/packages.html#package-entry-points
// node_modules/uicomponents/package.json{"exports": {".": {"sass": "./src/scss/index.scss",},"./colors.scss": {"sass": "./src/scss/_colors.scss",},"./theme/*.scss": {"sass": "./src/scss/theme/*.scss",},}}This allows a package user to write:
-
@use "pkg:uicomponents";
to import the root export. -@use "pkg:uicomponents/colors";
to import the colors partial. -@use "pkg:uicomponents/theme/purple";
to import a purple theme.Note that while library users can rely on the importer to resolve [partials](https://sass-lang.com/documentation/at-rules/use#partials), [index files](https://sass-lang.com/documentation/at-rules/use#index-files), and extensions, library authors must specify the entire file path in
exports
.In addition to the
sass
condition, thestyle
condition is also acceptable. Sass will match thedefault
condition if it's a relevant file type, but authors are discouraged from relying on this. Notably, the key order matters, and the importer will resolve to the first value with a key that issass
,style
, ordefault
, so you should always putdefault
last.To help package authors who haven't transitioned to package entry points using the
exports
field, the Node.js package importer provides several fallback options. If thepkg:
URL does not have a subpath, the Node.js package importer will look for asass
orstyle
key at the root ofpackage.json
.// node_modules/uicomponents/package.json{"sass": "./src/scss/index.scss",}This allows a user to write
@use "pkg:uicomponents";
to import theindex.scss
file.Finally, the Node.js package importer will look for an
index
file at the package root, resolving partials and extensions. For example, if the file_index.scss
exists in the package root ofuicomponents
, a user can import that with@use "pkg:uicomponents";
.If a
pkg:
URL includes a subpath that doesn't have a match in package entry points, the Node.js importer will attempt to find that file relative to the package root, resolving for file extensions, partials and index files. For example, if the filesrc/sass/_colors.scss
exists in theuicomponents
package, a user can import that file using `@use "pkg:uicomponents/src/sass/colors";`.dart: "1.71.0", node: false Importer
constructor
constructor(entryPointDirectory?: string);
The NodePackageImporter has an optional
entryPointDirectory
option, which is the directory where the Node Package Importer should start when resolvingpkg:
URLs in sources other than files on disk. This will be used as theparentURL
in the [Node Module Resolution](https://nodejs.org/api/esm.html#resolution-algorithm-specification) algorithm.In order to be found by the Node Package Importer, a package will need to be inside a node_modules folder located in the
entryPointDirectory
, or one of its parent directories, up to the filesystem root.Relative paths will be resolved relative to the current working directory. If a path is not provided, this defaults to the parent directory of the Node.js entrypoint. If that's not available, this will throw an error.
class SassArgumentList
class SassArgumentList extends SassList {}
Sass's [argument list type](https://sass-lang.com/documentation/values/lists#argument-lists).
An argument list comes from a rest argument. It's distinct from a normal SassList in that it may contain a keyword map as well as the positional arguments.
Custom Function
constructor
constructor(contents: any, keywords: any, separator?: ListSeparator);
Creates a new argument list.
Parameter contents
The positional arguments that make up the primary contents of the list. This may be either a plain JavaScript array or an immutable List from the [
immutable
package](https://immutable-js.com/).Parameter keywords
The keyword arguments attached to this argument list, whose names should exclude
$
. This can be either a plain JavaScript object with argument names as fields, or an immutable OrderedMap from the [immutable
package](https://immutable-js.com/)Parameter separator
The separator for this list. Defaults to
','
.
property keywords
readonly keywords: OrderedMap<string, Value>;
The keyword arguments attached to this argument list.
The argument names don't include
$
.Returns
An immutable OrderedMap from the [
immutable
package](https://immutable-js.com/).
class SassBoolean
class SassBoolean extends Value {}
Sass's [boolean type](https://sass-lang.com/documentation/values/booleans).
Custom Function
property value
readonly value: boolean;
Whether this value is
true
orfalse
.
class SassCalculation
class SassCalculation extends Value {}
Sass's [calculation type](https://sass-lang.com/documentation/values/calculations).
Note: in the JS API calculations are not simplified eagerly. This also means that unsimplified calculations are not equal to the numbers they would be simplified to.
Custom Function
property arguments
readonly arguments: List<CalculationValue>;
Returns a list of the calculation's
arguments
property name
readonly name: string;
Returns the calculation's
name
field.
method calc
static calc: (argument: CalculationValue) => SassCalculation;
Creates a value that represents
calc(argument)
.Returns
A calculation with the name
calc
andargument
as its single argument.Throws
Error
ifargument
is a quoted SassString
method clamp
static clamp: ( min: CalculationValue, value?: CalculationValue, max?: CalculationValue) => SassCalculation;
Creates a value that represents
clamp(value, min, max)
.Returns
A calculation with the name
clamp
andmin
,value
, andmax
as it's arguments, excluding any arguments that are undefined.Throws
Error
if any ofvalue
,min
, ormax
are a quoted SassString.Throws
Error
ifvalue
is undefined andmax
is not undefined.Throws
Error
if eithervalue
ormax
is undefined and neithermin
norvalue
is a SassString or CalculationInterpolation.
method max
static max: ( arguments: CalculationValue[] | List<CalculationValue>) => SassCalculation;
Creates a value that represents
max(arguments...)
.Returns
A calculation with the name
max
andarguments
as its arguments.Throws
Error
ifarguments
contains a quoted SassString
method min
static min: ( arguments: CalculationValue[] | List<CalculationValue>) => SassCalculation;
Creates a value that represents
min(arguments...)
.Returns
A calculation with the name
min
andarguments
as its arguments.Throws
Error
ifarguments
contains a quoted SassString
class SassColor
class SassColor extends Value {}
Sass's [color type](https://sass-lang.com/documentation/values/colors).
No matter what representation was originally used to create this color, all of its channels are accessible.
Custom Function
constructor
constructor(options: { red: number | null; green: number | null; blue: number | null; alpha?: number | null; space?: 'rgb';});
Creates an [RGB color].
If
space
is missing, **only**undefined
should be used to indicate thatalpha
isn't passed. Ifnull
is used instead, it will be treated as a [missing component]. See [breaking changes] for details.If
space
is defined andnull
is passed for any component, it will be treated as a [missing component].[RGB color]: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/rgb [missing component]: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#missing_color_components [breaking changes]: /documentation/breaking-changes/null-alpha
Throws
Error
ifalpha
is set and isn'tnull
or a number between0
and1
.
constructor
constructor(options: { hue: number | null; saturation: number | null; lightness: number | null; alpha?: number | null; space?: ColorSpaceHsl;});
Creates an [HSL color].
If
space
is missing, **only**undefined
should be used to indicate thatalpha
isn't passed. Ifnull
is used instead, it will be treated as a [missing component]. See [breaking changes] for details.If
space
is defined andnull
is passed for any component, it will be treated as a [missing component].[HSL color]: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/hsl [missing component]: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#missing_color_components [breaking changes]: /documentation/breaking-changes/null-alpha
Throws
Error
ifalpha
is set and isn'tnull
or a number between0
and1
.
constructor
constructor(options: { hue: number | null; whiteness: number | null; blackness: number | null; alpha?: number | null; space?: ColorSpaceHwb;});
Creates an [HWB color].
If
space
is missing, **only**undefined
should be used to indicate thatalpha
isn't passed. Ifnull
is used instead, it will be treated as a [missing component]. See [breaking changes] for details.If
space
is defined andnull
is passed for any component, it will be treated as a [missing component].[HWB color]: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/hwb [missing component]: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#missing_color_components [breaking changes]: /documentation/breaking-changes/null-alpha
Throws
Error
ifalpha
is set and isn'tnull
or a number between0
and1
.
constructor
constructor(options: { lightness: number | null; a: number | null; b: number | null; alpha?: number | null; space: ColorSpaceLab;});
Creates a [Lab] or [Oklab] color.
If
null
is passed for any component, it will be treated as a [missing component].[Lab]: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/lab [Oklab]: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/oklab [missing component]: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#missing_color_components
Throws
Error
ifalpha
is set and isn'tnull
or a number between0
and1
.
constructor
constructor(options: { lightness: number | null; chroma: number | null; hue: number | null; alpha?: number | null; space: ColorSpaceLch;});
Creates an [LCH] or [Oklch] color.
If
null
is passed for any component, it will be treated as a [missing component].[LCH]: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/lch [Oklch]: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/oklch [missing component]: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#missing_color_components
Throws
Error
ifalpha
is set and isn'tnull
or a number between0
and1
.
constructor
constructor(options: { red: number | null; green: number | null; blue: number | null; alpha?: number | null; space: Exclude<ColorSpaceRgb, 'rgb'>;});
Creates a color in a predefined [RGB color space].
If
null
is passed for any component, it will be treated as a [missing component].[RGB color space]: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/color#using_predefined_colorspaces_with_color [missing component]: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#missing_color_components
Throws
Error
ifalpha
is set and isn'tnull
or a number between0
and1
.
constructor
constructor(options: { x: number | null; y: number | null; z: number | null; alpha?: number | null; space: ColorSpaceXyz;});
Creates a color in a predefined [XYZ color space].
If
null
is passed for any component, it will be treated as a [missing component].[XYZ color space]: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/color#using_the_xyz_colorspace_with_color [missing component]: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#missing_color_components
Throws
Error
ifalpha
is set and isn'tnull
or a number between0
and1
.
property alpha
readonly alpha: number;
This color's alpha channel, between
0
and1
.
property blackness
readonly blackness: number;
This color's blackness in the HWB color space.
Deprecated
Use channel instead.
property blue
readonly blue: number;
This color's blue channel in the RGB color space.
Deprecated
Use channel instead.
property channels
readonly channels: List<number>;
A list of this color's channel values (excluding alpha), with [missing channels] converted to
0
.[missing channels]: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#missing_color_components
property channelsOrNull
readonly channelsOrNull: List<number>;
A list of this color's channel values (excluding alpha), with [missing channels] converted to
null
.[missing channels]: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#missing_color_components
property green
readonly green: number;
This color's green channel in the RGB color space.
Deprecated
Use channel instead.
property hue
readonly hue: number;
This color's hue in the HSL color space.
Deprecated
Use channel instead.
property isLegacy
readonly isLegacy: boolean;
A boolean indicating whether this color is in a legacy color space (
rgb
,hsl
, orhwb
).
property lightness
readonly lightness: number;
This color's lightness in the HSL color space.
Deprecated
Use channel instead.
property red
readonly red: number;
This color's red channel in the RGB color space.
Deprecated
Use channel instead.
property saturation
readonly saturation: number;
This color's saturation in the HSL color space.
Deprecated
Use channel instead.
property space
readonly space: KnownColorSpace;
The name of this color's space.
property whiteness
readonly whiteness: number;
This color's whiteness in the HWB color space.
Deprecated
Use channel instead.
method change
change: { ( options: { hue?: number; saturation?: number; lightness?: number; alpha?: number; } & { space?: ColorSpaceHsl } ): SassColor; ( options: { hue?: number; alpha?: number; whiteness?: number; blackness?: number; } & { space?: 'hwb' } ): SassColor; ( options: { lightness?: number; alpha?: number; a?: number; b?: number; } & { space?: ColorSpaceLab } ): SassColor; ( options: { hue?: number; lightness?: number; alpha?: number; chroma?: number; } & { space?: ColorSpaceLch } ): SassColor; ( options: { alpha?: number; red?: number; green?: number; blue?: number; } & { space?: ColorSpaceRgb } ): SassColor; ( options: { alpha?: number; x?: number; y?: number; z?: number } & { space?: ColorSpaceXyz; } ): SassColor;};
Returns a new color that's the result of changing one or more of this color's HSL channels.
Throws
Error
ifspace
is missing and this color is not in a legacy color space (rgb
,hsl
, orhwb
).Throws
Error
ifalpha
is set and isn'tnull
or a number between0
and1
.Returns a new color that's the result of changing one or more of this color's HWB channels.
Throws
Error
ifspace
is missing and this color is not in a legacy color space (rgb
,hsl
, orhwb
).Throws
Error
ifalpha
is set and isn'tnull
or a number between0
and1
.Returns a new color that's the result of changing one or more of this color's Lab channels.
Throws
Error
ifspace
is missing and this color is not in the Lab or Oklab color spaces.Throws
Error
ifalpha
is set and isn'tnull
or a number between0
and1
.Returns a new color that's the result of changing one or more of this color's LCH channels.
Throws
Error
ifspace
is missing and this color is not in the LCH or Oklch color spaces.Throws
Error
ifalpha
is set and isn'tnull
or a number between0
and1
.Returns a new color that's the result of changing one or more of this color's RGB channels.
Throws
Error
ifspace
is missing and this color is not in a legacy color space (rgb
,hsl
, orhwb
).Throws
Error
ifalpha
is set and isn'tnull
or a number between0
and1
.Returns a new color that's the result of changing one or more of this color's XYZ channels.
Throws
Error
ifspace
is missing and this color is not in an XYZ color space.Throws
Error
ifalpha
is set and isn'tnull
or a number between0
and1
.
method channel
channel: { (channel: ChannelName): number; (channel: ChannelNameHsl, options: { space: 'hsl' }): number; (channel: ChannelNameHwb, options: { space: 'hwb' }): number; (channel: ChannelNameLab, options: { space: ColorSpaceLab }): number; (channel: ChannelNameLch, options: { space: ColorSpaceLch }): number; (channel: ChannelNameRgb, options: { space: ColorSpaceRgb }): number; (channel: ChannelNameXyz, options: { space: ColorSpaceXyz }): number;};
Returns the value of a single specified
channel
of this color, with [missing channels] converted to0
.[missing channels]: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#missing_color_components
Throws
Error
ifchannel
is notalpha
or a channel in this color's space.Returns the value of a single specified
channel
of this color after converting this color to the specifiedspace
, with [missing channels] converted to0
.[missing channels]: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#missing_color_components
Throws
Error
ifchannel
is notalpha
or a channel inspace
.
method interpolate
interpolate: ( color2: SassColor, options?: { weight?: number; method?: HueInterpolationMethod }) => SassColor;
Returns a color partway between this color and
color2
according tomethod
, as defined by the CSS Color 4 [color interpolation] procedure.[color interpolation]: https://www.w3.org/TR/css-color-4/#interpolation
If
method
is missing and this color is in a rectangular color space (Lab, Oklab, RGB, and XYZ spaces),method
defaults to the color space of this color. Otherwise,method
defaults to a space separated list containing the color space of this color and the string "shorter".The
weight
is a number between 0 and 1 that indicates how much of this color should be in the resulting color. If omitted, it defaults to 0.5.
method isChannelMissing
isChannelMissing: (channel: ChannelName) => boolean;
Returns a boolean indicating whether a given channel value is a [missing channel].
[missing channel]: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#missing_color_components
method isChannelPowerless
isChannelPowerless: { (channel: ChannelName): boolean; (channel: ChannelNameHsl, options?: { space: 'hsl' }): boolean; (channel: ChannelNameHwb, options?: { space: 'hwb' }): boolean; (channel: ChannelNameLab, options?: { space: ColorSpaceLab }): boolean; (channel: ChannelNameLch, options?: { space: ColorSpaceLch }): boolean; (channel: ChannelNameRgb, options?: { space: ColorSpaceRgb }): boolean; (channel: ChannelNameXyz, options?: { space: ColorSpaceXyz }): boolean;};
Returns a boolean indicating whether a given
channel
is [powerless] in this color. This is a special state that's defined for individual color spaces, which indicates that a channel's value won't affect how a color is displayed.[powerless]: https://www.w3.org/TR/css-color-4/#powerless
method isInGamut
isInGamut: (space?: KnownColorSpace) => boolean;
Returns a boolean indicating whether this color is in-gamut (as opposed to having one or more of its channels out of bounds) for the specified
space
, or its current color space ifspace
is not specified.
method toGamut
toGamut: (options: { space?: KnownColorSpace; method: GamutMapMethod;}) => SassColor;
Returns a copy of this color, modified so it is in-gamut for the specified
space
—or the current color space ifspace
is not specified—usingmethod
to map out-of-gamut colors into the desired gamut.
method toSpace
toSpace: (space: KnownColorSpace) => SassColor;
Returns a new color that's the result of converting this color to the specified
space
.
class SassFunction
class SassFunction extends Value {}
Sass's [function type](https://sass-lang.com/documentation/values/functions).
**Heads up!** Although first-class Sass functions can be processed by custom functions, there's no way to invoke them outside of a Sass stylesheet.
Custom Function
constructor
constructor(signature: string, callback: (args: Value[]) => Value);
Creates a new first-class function that can be invoked using [
meta.call()
](https://sass-lang.com/documentation/modules/meta#call).Parameter signature
The function signature, like you'd write for the [
@function rule
](https://sass-lang.com/documentation/at-rules/function).Parameter callback
The callback that's invoked when this function is called, just like for a CustomFunction.
class SassList
class SassList extends Value {}
Sass's [list type](https://sass-lang.com/documentation/values/lists).
Custom Function
constructor
constructor( contents: any, options?: { separator?: ListSeparator; brackets?: boolean });
Creates a new list.
Parameter contents
The contents of the list. This may be either a plain JavaScript array or an immutable List from the [
immutable
package](https://immutable-js.com/).Parameter
options.separator - The separator to use between elements of this list. Defaults to
','
.Parameter
options.brackets - Whether the list has square brackets. Defaults to
false
.
constructor
constructor(options?: { separator?: ListSeparator; brackets?: boolean });
Creates an empty list.
Parameter
options.separator - The separator to use between elements of this list. Defaults to
','
.Parameter
options.brackets - Whether the list has square brackets. Defaults to
false
.
property separator
readonly separator: ListSeparator;
class SassMap
class SassMap extends Value {}
Sass's [map type](https://sass-lang.com/documentation/values/maps).
Custom Function
constructor
constructor(contents?: OrderedMap<Value, Value>);
Creates a new map.
Parameter contents
The contents of the map. This is an immutable
OrderedMap
from the [immutable
package](https://immutable-js.com/). Defaults to an empty map.
property contents
readonly contents: OrderedMap<Value, Value>;
Returns the contents of this map as an immutable OrderedMap from the [
immutable
package](https://immutable-js.com/).
method get
get: { (key: Value): Value | undefined; (index: number): SassList };
Returns the value associated with
key
in this map, orundefined
ifkey
isn't in the map.This is a shorthand for
this.contents.get(key)
, although it may be more efficient in some cases.Inherited from Value.get.
method tryMap
tryMap: () => SassMap;
class SassMixin
class SassMixin extends Value {}
Sass's [mixin type](https://sass-lang.com/documentation/values/mixins).
Custom Function
constructor
constructor();
It is not possible to construct a Sass mixin outside of Sass. Attempting to construct one will throw an exception.
class SassNumber
class SassNumber extends Value {}
Sass's [number type](https://sass-lang.com/documentation/values/numbers).
Custom Function
constructor
constructor( value: number, unit?: | string | { numeratorUnits?: string[] | List<string>; denominatorUnits?: string[] | List<string>; });
Creates a new number with more complex units than just a single numerator.
Upon construction, any compatible numerator and denominator units are simplified away according to the conversion factor between them.
Parameter value
The number's numeric value.
Parameter unit
If this is a string, it's used as the single numerator unit for the number.
Parameter
unit.numeratorUnits - If passed, these are the numerator units to use for the number. This may be either a plain JavaScript array or an immutable List from the [
immutable
package](https://immutable-js.com/).Parameter
unit.denominatorUnits - If passed, these are the denominator units to use for the number. This may be either a plain JavaScript array or an immutable List from the [
immutable
package](https://immutable-js.com/).
property asInt
readonly asInt: number;
property denominatorUnits
readonly denominatorUnits: List<string>;
This number's denominator units as an immutable List from the [
immutable
package](https://immutable-js.com/).
property hasUnits
readonly hasUnits: boolean;
Whether this number has any numerator or denominator units.
property isInt
readonly isInt: boolean;
Whether value is an integer according to Sass's equality logic.
property numeratorUnits
readonly numeratorUnits: List<string>;
This number's numerator units as an immutable List from the [
immutable
package](https://immutable-js.com/).
property value
readonly value: number;
This number's numeric value.
method assertInRange
assertInRange: (min: number, max: number, name?: string) => number;
method assertInt
assertInt: (name?: string) => number;
method assertNoUnits
assertNoUnits: (name?: string) => SassNumber;
If this number has no units, returns it. Otherwise, throws an error.
Parameter name
The name of the function argument
this
came from (without the$
) if it came from an argument. Used for error reporting.
method assertUnit
assertUnit: (unit: string, name?: string) => SassNumber;
If this number has
unit
as its only unit (and as a numerator), returns this number. Otherwise, throws an error.Parameter name
The name of the function argument
this
came from (without the$
) if it came from an argument. Used for error reporting.
method coerce
coerce: ( newNumerators: string[] | List<string>, newDenominators: string[] | List<string>, name?: string) => SassNumber;
Returns a copy of this number, converted to the units represented by
newNumerators
andnewDenominators
.Unlike convert this does *not* throw an error if this number is unitless and either
newNumerators
ornewDenominators
are not empty, or vice-versa. Instead, it treats all unitless numbers as convertible to and from all units without changing the value.Parameter newNumerators
The numerator units to convert this number to. This may be either a plain JavaScript array or an immutable List from the [
immutable
package](https://immutable-js.com/).Parameter newDenominators
The denominator units to convert this number to. This may be either a plain JavaScript array or an immutable List from the [
immutable
package](https://immutable-js.com/).Parameter name
The name of the function argument
this
came from (without the$
) if it came from an argument. Used for error reporting.Throws
Error
if this number's units are incompatible withnewNumerators
andnewDenominators
.
method coerceToMatch
coerceToMatch: ( other: SassNumber, name?: string, otherName?: string) => SassNumber;
Returns a copy of this number, converted to the units represented by
newNumerators
andnewDenominators
.Unlike convertToMatch this does *not* throw an error if this number is unitless and either
newNumerators
ornewDenominators
are not empty, or vice-versa. Instead, it treats all unitless numbers as convertible to and from all units without changing the value.Parameter name
The name of the function argument
this
came from (without the$
) if it came from an argument. Used for error reporting.Parameter otherName
The name of the function argument
other
came from (without the$
) if it came from an argument. Used for error reporting.Throws
Error
if this number's units are incompatible withother
's units.
method coerceValue
coerceValue: ( newNumerators: string[] | List<string>, newDenominators: string[] | List<string>, name?: string) => number;
Returns value, converted to the units represented by
newNumerators
andnewDenominators
.Unlike convertValue this does *not* throw an error if this number is unitless and either
newNumerators
ornewDenominators
are not empty, or vice-versa. Instead, it treats all unitless numbers as convertible to and from all units without changing the value.Parameter newNumerators
The numerator units to convert value to. This may be either a plain JavaScript array or an immutable List from the [
immutable
package](https://immutable-js.com/).Parameter newDenominators
The denominator units to convert value to. This may be either a plain JavaScript array or an immutable List from the [
immutable
package](https://immutable-js.com/).Parameter name
The name of the function argument
this
came from (without the$
) if it came from an argument. Used for error reporting.Throws
Error
if this number's units are incompatible withnewNumerators
andnewDenominators
.
method coerceValueToMatch
coerceValueToMatch: ( other: SassNumber, name?: string, otherName?: string) => number;
Returns value, converted to the units represented by
newNumerators
andnewDenominators
.Unlike convertValueToMatch this does *not* throw an error if this number is unitless and either
newNumerators
ornewDenominators
are not empty, or vice-versa. Instead, it treats all unitless numbers as convertible to and from all units without changing the value.Parameter name
The name of the function argument
this
came from (without the$
) if it came from an argument. Used for error reporting.Parameter otherName
The name of the function argument
other
came from (without the$
) if it came from an argument. Used for error reporting.Throws
Error
if this number's units are incompatible withother
's units.
method compatibleWithUnit
compatibleWithUnit: (unit: string) => boolean;
Whether this has exactly one numerator unit, and that unit is compatible with
unit
.
method convert
convert: ( newNumerators: string[] | List<string>, newDenominators: string[] | List<string>, name?: string) => SassNumber;
Returns a copy of this number, converted to the units represented by
newNumerators
andnewDenominators
.Parameter newNumerators
The numerator units to convert this number to. This may be either a plain JavaScript array or an immutable List from the [
immutable
package](https://immutable-js.com/).Parameter newDenominators
The denominator units to convert this number to. This may be either a plain JavaScript array or an immutable List from the [
immutable
package](https://immutable-js.com/).Parameter name
The name of the function argument
this
came from (without the$
) if it came from an argument. Used for error reporting.Throws
Error
if this number's units are incompatible withnewNumerators
andnewDenominators
; or if this number is unitless and eithernewNumerators
ornewDenominators
are not empty, or vice-versa.
method convertToMatch
convertToMatch: ( other: SassNumber, name?: string, otherName?: string) => SassNumber;
Returns a copy of this number, converted to the same units as
other
.Parameter name
The name of the function argument
this
came from (without the$
) if it came from an argument. Used for error reporting.Parameter otherName
The name of the function argument
other
came from (without the$
) if it came from an argument. Used for error reporting.Throws
Error
if this number's units are incompatible withother
's units, or if either number is unitless but the other is not.
method convertValue
convertValue: ( newNumerators: string[] | List<string>, newDenominators: string[] | List<string>, name?: string) => number;
Returns value, converted to the units represented by
newNumerators
andnewDenominators
.Parameter newNumerators
The numerator units to convert value to. This may be either a plain JavaScript array or an immutable List from the [
immutable
package](https://immutable-js.com/).Parameter newDenominators
The denominator units to convert value to. This may be either a plain JavaScript array or an immutable List from the [
immutable
package](https://immutable-js.com/).Parameter name
The name of the function argument
this
came from (without the$
) if it came from an argument. Used for error reporting.Throws
Error
if this number's units are incompatible withnewNumerators
andnewDenominators
; or if this number is unitless and eithernewNumerators
ornewDenominators
are not empty, or vice-versa.
method convertValueToMatch
convertValueToMatch: ( other: SassNumber, name?: string, otherName?: string) => number;
Returns value, converted to the same units as
other
.Parameter name
The name of the function argument
this
came from (without the$
) if it came from an argument. Used for error reporting.Parameter otherName
The name of the function argument
other
came from (without the$
) if it came from an argument. Used for error reporting.Throws
Error
if this number's units are incompatible withother
's units, or if either number is unitless but the other is not.
method hasUnit
hasUnit: (unit: string) => boolean;
Whether this number has
unit
as its only unit (and as a numerator).
class SassString
class SassString extends Value {}
Sass's [string type](https://sass-lang.com/documentation/values/strings).
Custom Function
constructor
constructor(text: string, options?: { quotes?: boolean });
Creates a new string.
Parameter text
The contents of the string. For quoted strings, this is the semantic content—any escape sequences that were been written in the source text are resolved to their Unicode values. For unquoted strings, though, escape sequences are preserved as literal backslashes.
Parameter
options.quotes - Whether the string is quoted. Defaults to
true
.
constructor
constructor(options?: { quotes?: boolean });
Creates an empty string.
Parameter
options.quotes - Whether the string is quoted. Defaults to
true
.
property hasQuotes
readonly hasQuotes: boolean;
Whether this string has quotes.
property sassLength
readonly sassLength: number;
Sass's notion of this string's length.
Sass treats strings as a series of Unicode code points while JavaScript treats them as a series of UTF-16 code units. For example, the character U+1F60A SMILING FACE WITH SMILING EYES is a single Unicode code point but is represented in UTF-16 as two code units (
0xD83D
and0xDE0A
). So in JavaScript,"n😊b".length
returns4
, whereas in Sassstring.length("n😊b")
returns3
.
property text
readonly text: string;
The contents of the string.
For quoted strings, this is the semantic content—any escape sequences that were been written in the source text are resolved to their Unicode values. For unquoted strings, though, escape sequences are preserved as literal backslashes.
This difference allows us to distinguish between identifiers with escapes, such as
url\u28 http://example.com\u29
, and unquoted strings that contain characters that aren't valid in identifiers, such asurl(http://example.com)
. Unfortunately, it also means that we don't considerfoo
andf\6F\6F
the same string.
method sassIndexToStringIndex
sassIndexToStringIndex: (sassIndex: Value, name?: string) => number;
Converts
sassIndex
to a JavaScript index into text.Sass indices are one-based, while JavaScript indices are zero-based. Sass indices may also be negative in order to index from the end of the string.
In addition, Sass indices refer to Unicode code points while JavaScript string indices refer to UTF-16 code units. For example, the character U+1F60A SMILING FACE WITH SMILING EYES is a single Unicode code point but is represented in UTF-16 as two code units (
0xD83D
and0xDE0A
). So in JavaScript,"n😊b".charCodeAt(1)
returns0xD83D
, whereas in Sassstring.slice("n😊b", 1, 1)
returns"😊"
.This function converts Sass's code point indices to JavaScript's code unit indices. This means it's O(n) in the length of
text
.Throws
Error
- IfsassIndex
isn't a number, if that number isn't an integer, or if that integer isn't a valid index for this string.
class Value
abstract class Value implements ValueObject {}
The abstract base class of Sass's value types.
This is passed to and returned by CustomFunctions, which are passed into the Sass implementation using Options.functions.
Custom Function
constructor
protected constructor();
property asList
readonly asList: List<Value>;
This value as a list.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
Returns
An immutable List from the [
immutable
package](https://immutable-js.com/).
property hasBrackets
readonly hasBrackets: boolean;
Whether this value as a list has brackets.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
property isTruthy
readonly isTruthy: boolean;
Whether the value counts as
true
in an@if
statement and other contexts.
property realNull
readonly realNull: Value;
Returns JavaScript's
null
value if this is sassNull, and returnsthis
otherwise.
property separator
readonly separator: ListSeparator;
The separator for this value as a list.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
method assertBoolean
assertBoolean: (name?: string) => SassBoolean;
Throws if
this
isn't a SassBoolean.**Heads up!** Functions should generally use isTruthy rather than requiring a literal boolean.
Parameter name
The name of the function argument
this
came from (without the$
) if it came from an argument. Used for error reporting.
method assertCalculation
assertCalculation: (name?: string) => SassCalculation;
Throws if
this
isn't a SassCalculation.Parameter name
The name of the function argument
this
came from (without the$
) if it came from an argument. Used for error reporting.
method assertColor
assertColor: (name?: string) => SassColor;
Throws if
this
isn't a SassColor.Parameter name
The name of the function argument
this
came from (without the$
) if it came from an argument. Used for error reporting.
method assertFunction
assertFunction: (name?: string) => SassFunction;
Throws if
this
isn't a SassFunction.Parameter name
The name of the function argument
this
came from (without the$
) if it came from an argument. Used for error reporting.
method assertMap
assertMap: (name?: string) => SassMap;
Throws if
this
isn't a SassMap.Parameter name
The name of the function argument
this
came from (without the$
) if it came from an argument. Used for error reporting.
method assertMixin
assertMixin: (name?: string) => SassMixin;
Throws if
this
isn't a SassMixin.Parameter name
The name of the function argument
this
came from (without the$
) if it came from an argument. Used for error reporting.
method assertNumber
assertNumber: (name?: string) => SassNumber;
Throws if
this
isn't a SassNumber.Parameter name
The name of the function argument
this
came from (without the$
) if it came from an argument. Used for error reporting.
method assertString
assertString: (name?: string) => SassString;
Throws if
this
isn't a SassString.Parameter name
The name of the function argument
this
came from (without the$
) if it came from an argument. Used for error reporting.
method equals
equals: (other: Value) => boolean;
Returns whether
this
represents the same value asother
.
method get
get: (index: number) => Value | undefined;
Returns the value at index
index
in this value as a list, orundefined
ifindex
isn't valid for this list.All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
This is a shorthand for
this.asList.get(index)
, although it may be more efficient in some cases.**Heads up!** This method uses the same indexing conventions as the
immutable
package: unlike Sass the index of the first element is 0, but like Sass negative numbers index from the end of the list.
method hashCode
hashCode: () => number;
Returns a hash code that can be used to store
this
in a hash map.
method sassIndexToListIndex
sassIndexToListIndex: (sassIndex: Value, name?: string) => number;
Converts
sassIndex
into a JavaScript-style index into the list returned by asList.Sass indexes are one-based, while JavaScript indexes are zero-based. Sass indexes may also be negative in order to index from the end of the list.
Parameter sassIndex
The Sass-style index into this as a list.
Parameter name
The name of the function argument
sassIndex
came from (without the$
) if it came from an argument. Used for error reporting.Throws
Error
IfsassIndex
isn't a number, if that number isn't an integer, or if that integer isn't a valid index for asList.
method toString
toString: () => string;
method tryMap
tryMap: () => SassMap | null;
Returns
this
as a map if it counts as one (empty lists count as empty maps) ornull
if it doesn't.
class Version
class Version {}
A semantic version of the compiler.
Messages dart: "1.74.0", node: false
constructor
constructor(major: number, minor: number, patch: number);
Constructs a new version.
All components must be non-negative integers.
Parameter major
The major version.
Parameter minor
The minor version.
Parameter patch
The patch version.
property major
readonly major: number;
property minor
readonly minor: number;
property patch
readonly patch: number;
method parse
static parse: (version: string) => Version;
Parses a version from a string.
This throws an error if a valid version can't be parsed.
Parameter version
A string in the form "major.minor.patch".
Interfaces
interface CanonicalizeContext
interface CanonicalizeContext {}
Contextual information passed to Importer.canonicalize and FileImporter.findFileUrl. Not all importers will need this information to resolve loads, but some may find it useful.
property containingUrl
containingUrl: URL | null;
The canonical URL of the file that contains the load, if that information is available.
For an Importer, this is only passed when the
url
parameter is a relative URL _or_ when its [URL scheme] is included in Importer.nonCanonicalScheme. This ensures that canonical URLs are always resolved the same way regardless of context.[URL scheme]: https://developer.mozilla.org/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_URL#scheme
For a FileImporter, this is always available as long as Sass knows the canonical URL of the containing file.
property fromImport
fromImport: boolean;
Whether this is being invoked because of a Sass
@import
rule, as opposed to a@use
or@forward
rule.This should *only* be used for determining whether or not to load [import-only files](https://sass-lang.com/documentation/at-rules/import#import-only-files).
interface CompileResult
interface CompileResult {}
The result of compiling Sass to CSS. Returned by compile, compileAsync, compileString, and compileStringAsync.
Compile
property css
css: string;
The generated CSS.
Note that this *never* includes a
sourceMapUrl
comment—it's up to the caller to determine where to save the source map and how to link to it from the stylesheet.
property loadedUrls
loadedUrls: URL[];
The canonical URLs of all the stylesheets that were loaded during the Sass compilation. The order of these URLs is not guaranteed.
property sourceMap
sourceMap?: RawSourceMap;
The object representation of the source map that maps locations in the generated CSS back to locations in the Sass source code.
This typically uses absolute
file:
URLs to refer to Sass files, although this can be controlled by having a custom Importer return ImporterResult.sourceMapUrl.This is set if and only if Options.sourceMap is
true
.
interface Deprecation
interface Deprecation< id extends keyof Deprecations = keyof Deprecations, status extends DeprecationStatus = DeprecationStatus> {}
A deprecated feature in the language.
Messages dart: "1.74.0", node: false
property deprecatedIn
deprecatedIn: status extends 'future' | 'user' ? null : Version;
The version this deprecation first became active in.
property description
description?: string;
A human-readable description of this deprecation.
property id
id: id;
The unique ID of this deprecation.
property obsoleteIn
obsoleteIn: status extends 'obsolete' ? Version : null;
The version this deprecation became obsolete in.
property status
status: status;
The current status of this deprecation.
interface Deprecations
interface Deprecations {}
All of the deprecation types currently used by Sass.
Any of these IDs or the deprecation objects they point to can be passed to
fatalDeprecations
,futureDeprecations
, orsilenceDeprecations
.
property 'abs-percent'
'abs-percent': Deprecation<'abs-percent'>;
Deprecation for passing percentages to the Sass abs() function.
This deprecation became active in Dart Sass 1.65.0.
property 'bogus-combinators'
'bogus-combinators': Deprecation<'bogus-combinators'>;
Deprecation for leading, trailing, and repeated combinators.
This deprecation became active in Dart Sass 1.54.0.
property 'call-string'
'call-string': Deprecation<'call-string'>;
Deprecation for passing a string directly to meta.call().
This deprecation was active in the first version of Dart Sass.
property 'color-4-api'
'color-4-api': Deprecation<'color-4-api'>;
Deprecation for certain uses of built-in sass:color functions.
This deprecation became active in Dart Sass 1.79.0.
property 'color-functions'
'color-functions': Deprecation<'color-functions'>;
Deprecation for using global color functions instead of sass:color.
This deprecation became active in Dart Sass 1.79.0.
property 'color-module-compat'
'color-module-compat': Deprecation<'color-module-compat'>;
Deprecation for using color module functions in place of plain CSS functions.
This deprecation became active in Dart Sass 1.23.0.
property 'css-function-mixin'
'css-function-mixin': Deprecation<'css-function-mixin'>;
Deprecation for function and mixin names beginning with --.
This deprecation became active in Dart Sass 1.76.0.
property 'duplicate-var-flags'
'duplicate-var-flags': Deprecation<'duplicate-var-flags'>;
Deprecation for using !default or !global multiple times for one variable.
This deprecation became active in Dart Sass 1.62.0.
property 'feature-exists'
'feature-exists': Deprecation<'feature-exists'>;
Deprecation for meta.feature-exists
This deprecation became active in Dart Sass 1.78.0.
property 'fs-importer-cwd'
'fs-importer-cwd': Deprecation<'fs-importer-cwd'>;
Deprecation for using the current working directory as an implicit load path.
This deprecation became active in Dart Sass 1.73.0.
property 'function-units'
'function-units': Deprecation<'function-units'>;
Deprecation for passing invalid units to built-in functions.
This deprecation became active in Dart Sass 1.56.0.
property 'global-builtin'
'global-builtin': Deprecation<'global-builtin'>;
Deprecation for global built-in functions that are available in sass: modules.
This deprecation became active in Dart Sass 1.80.0.
property 'legacy-js-api'
'legacy-js-api': Deprecation<'legacy-js-api'>;
Deprecation for legacy JS API.
This deprecation became active in Dart Sass 1.79.0.
property 'mixed-decls'
'mixed-decls': Deprecation<'mixed-decls'>;
Deprecation for declarations after or between nested rules.
This deprecation became active in Dart Sass 1.77.7.
property 'moz-document'
'moz-document': Deprecation<'moz-document'>;
Deprecation for @-moz-document.
This deprecation became active in Dart Sass 1.7.2.
property 'new-global'
'new-global': Deprecation<'new-global'>;
Deprecation for declaring new variables with !global.
This deprecation became active in Dart Sass 1.17.2.
property 'null-alpha'
'null-alpha': Deprecation<'null-alpha'>;
Deprecation for passing null as alpha in the JS API.
This deprecation became active in Dart Sass 1.62.3.
property 'relative-canonical'
'relative-canonical': Deprecation<'relative-canonical'>;
Deprecation for imports using relative canonical URLs.
This deprecation became active in Dart Sass 1.14.2.
property 'slash-div'
'slash-div': Deprecation<'slash-div'>;
Deprecation for / operator for division.
This deprecation became active in Dart Sass 1.33.0.
property 'strict-unary'
'strict-unary': Deprecation<'strict-unary'>;
Deprecation for ambiguous + and - operators.
This deprecation became active in Dart Sass 1.55.0.
property 'user-authored'
'user-authored': Deprecation<'user-authored', 'user'>;
Used for any user-emitted deprecation warnings.
property elseif
elseif: Deprecation<'elseif'>;
Deprecation for @elseif.
This deprecation became active in Dart Sass 1.3.2.
property import
import: Deprecation<'import'>;
Deprecation for rules.
This deprecation became active in Dart Sass 1.80.0.
interface FileImporter
interface FileImporter<sync extends 'sync' | 'async' = 'sync' | 'async'> {}
A special type of importer that redirects all loads to existing files on disk. Although this is less powerful than a full Importer, it automatically takes care of Sass features like resolving partials and file extensions and of loading the file from disk.
Like all importers, this implements custom Sass loading logic for [
@use
rules](https://sass-lang.com/documentation/at-rules/use) and [@import
rules](https://sass-lang.com/documentation/at-rules/import). It can be passed to Options.importers or StringOptions.importer.Example 1
const {pathToFileURL} = require('url');sass.compile('style.scss', {importers: [{// An importer that redirects relative URLs starting with "~" to// `node_modules`.findFileUrl(url) {if (!url.startsWith('~')) return null;return new URL(url.substring(1), pathToFileURL('node_modules'));}}]});Importer
property canonicalize
canonicalize?: never;
method findFileUrl
findFileUrl: ( url: string, context: CanonicalizeContext) => PromiseOr<URL | null, sync>;
A callback that's called to partially resolve a load (such as [
@use
](https://sass-lang.com/documentation/at-rules/use) or [@import
](https://sass-lang.com/documentation/at-rules/import)) to a file on disk.Unlike an Importer, the compiler will automatically handle relative loads for a FileImporter. See Options.importers for more details on the way loads are resolved.
Parameter url
The loaded URL. Since this might be relative, it's represented as a string rather than a URL object.
Returns
An absolute
file:
URL if this importer recognizes theurl
. This may be only partially resolved: the compiler will automatically look for [partials](https://sass-lang.com/documentation/at-rules/use#partials), [index files](https://sass-lang.com/documentation/at-rules/use#index-files), and file extensions based on the returned URL. An importer may also return a fully resolved URL if it so chooses.If this importer doesn't recognize the URL, it should return
null
instead to allow other importers or load paths to handle it.This may also return a
Promise
, but if it does the importer may only be passed to compileAsync and compileStringAsync, not compile or compileString.Throws
any - If this importer recognizes
url
but determines that it's invalid, it may throw an exception that will be wrapped by Sass. If the exception object has amessage
property, it will be used as the wrapped exception's message; otherwise, the exception object'stoString()
will be used. This means it's safe for importers to throw plain strings.
interface Importer
interface Importer<sync extends 'sync' | 'async' = 'sync' | 'async'> {}
An object that implements custom Sass loading logic for [
@use
rules](https://sass-lang.com/documentation/at-rules/use) and [@import
rules](https://sass-lang.com/documentation/at-rules/import). It can be passed to Options.importers or StringOptions.importer.Importers that simply redirect to files on disk are encouraged to use the FileImporter interface instead.
### Resolving a Load
This is the process of resolving a load using a custom importer:
- The compiler encounters
@use "db:foo/bar/baz"
. - It calls canonicalize with"db:foo/bar/baz"
. - canonicalize returnsnew URL("db:foo/bar/baz/_index.scss")
. - If the compiler has already loaded a stylesheet with this canonical URL, it re-uses the existing module. - Otherwise, it calls load with `new URL("db:foo/bar/baz/_index.scss")`. - load returns an ImporterResult that the compiler uses as the contents of the module.See Options.importers for more details on the way loads are resolved using multiple importers and load paths.
Example 1
sass.compile('style.scss', {// An importer for URLs like `bgcolor:orange` that generates a// stylesheet with the given background color.importers: [{canonicalize(url) {if (!url.startsWith('bgcolor:')) return null;return new URL(url);},load(canonicalUrl) {return {contents: `body {background-color: ${canonicalUrl.pathname}}`,syntax: 'scss'};}}]});Importer
property findFileUrl
findFileUrl?: never;
property nonCanonicalScheme
nonCanonicalScheme?: string | string[];
A URL scheme or set of schemes (without the
:
) that this importer promises never to use for URLs returned by canonicalize. If it does return a URL with one of these schemes, that's an error.If this is set, any call to canonicalize for a URL with a non-canonical scheme will be passed CanonicalizeContext.containingUrl if it's known.
These schemes may only contain lowercase ASCII letters, ASCII numerals,
+
,-
, and.
. They may not be empty.
method canonicalize
canonicalize: ( url: string, context: CanonicalizeContext) => PromiseOr<URL | null, sync>;
If
url
is recognized by this importer, returns its canonical format.If Sass has already loaded a stylesheet with the returned canonical URL, it re-uses the existing parse tree (and the loaded module for
@use
). This means that importers **must ensure** that the same canonical URL always refers to the same stylesheet, *even across different importers*. As such, importers are encouraged to use unique URL schemes to disambiguate between one another.As much as possible, custom importers should canonicalize URLs the same way as the built-in filesystem importer:
- The importer should look for stylesheets by adding the prefix
_
to the URL's basename, and by adding the extensions.sass
and.scss
if the URL doesn't already have one of those extensions. For example, if the URL wasfoo/bar/baz
, the importer would look for: -foo/bar/baz.sass
-foo/bar/baz.scss
-foo/bar/_baz.sass
-foo/bar/_baz.scss
If the URL was
foo/bar/baz.scss
, the importer would just look for: -foo/bar/baz.scss
-foo/bar/_baz.scss
If the importer finds a stylesheet at more than one of these URLs, it should throw an exception indicating that the URL is ambiguous. Note that if the extension is explicitly specified, a stylesheet with the opposite extension is allowed to exist.
- If none of the possible paths is valid, the importer should perform the same resolution on the URL followed by
/index
. In the example above, it would look for: -foo/bar/baz/index.sass
-foo/bar/baz/index.scss
-foo/bar/baz/_index.sass
-foo/bar/baz/_index.scss
As above, if the importer finds a stylesheet at more than one of these URLs, it should throw an exception indicating that the import is ambiguous.
If no stylesheets are found, the importer should return
null
.Calling canonicalize multiple times with the same URL must return the same result. Calling canonicalize with a URL returned by a previous call to canonicalize must return that URL.
Relative loads in stylesheets loaded from an importer are handled by resolving the loaded URL relative to the canonical URL of the stylesheet that contains it, and passing that URL back to the importer's canonicalize method. For example, suppose the "Resolving a Load" example above returned a stylesheet that contained `@use "mixins"`:
- The compiler resolves the URL
mixins
relative to the current stylesheet's canonical URLdb:foo/bar/baz/_index.scss
to getdb:foo/bar/baz/mixins
. - It calls canonicalize with"db:foo/bar/baz/mixins"
. - canonicalize returnsnew URL("db:foo/bar/baz/_mixins.scss")
.Because of this, canonicalize must return a meaningful result when called with a URL relative to one returned by an earlier call to canonicalize.
Parameter url
The loaded URL. Since this might be relative, it's represented as a string rather than a URL object.
Returns
An absolute URL if this importer recognizes the
url
, ornull
if it doesn't. If this returnsnull
, other importers or load paths may handle the load.This may also return a
Promise
, but if it does the importer may only be passed to compileAsync and compileStringAsync, not compile or compileString.Throws
any - If this importer recognizes
url
but determines that it's invalid, it may throw an exception that will be wrapped by Sass. If the exception object has amessage
property, it will be used as the wrapped exception's message; otherwise, the exception object'stoString()
will be used. This means it's safe for importers to throw plain strings.
method load
load: (canonicalUrl: URL) => PromiseOr<ImporterResult | null, sync>;
Loads the Sass text for the given
canonicalUrl
, or returnsnull
if this importer can't find the stylesheet it refers to.Parameter canonicalUrl
The canonical URL of the stylesheet to load. This is guaranteed to come from a call to canonicalize, although not every call to canonicalize will result in a call to load.
Returns
The contents of the stylesheet at
canonicalUrl
if it can be loaded, ornull
if it can't.This may also return a
Promise
, but if it does the importer may only be passed to compileAsync and compileStringAsync, not compile or compileString.Throws
any - If this importer finds a stylesheet at
url
but it fails to load for some reason, or ifurl
is uniquely associated with this importer but doesn't refer to a real stylesheet, the importer may throw an exception that will be wrapped by Sass. If the exception object has amessage
property, it will be used as the wrapped exception's message; otherwise, the exception object'stoString()
will be used. This means it's safe for importers to throw plain strings.
interface ImporterResult
interface ImporterResult {}
The result of successfully loading a stylesheet with an Importer.
Importer
property contents
contents: string;
The contents of the stylesheet.
property sourceMapUrl
sourceMapUrl?: URL;
The URL to use to link to the loaded stylesheet's source code in source maps. A
file:
URL is ideal because it's accessible to both browsers and other build tools, but anhttp:
URL is also acceptable.If this isn't set, it defaults to a
data:
URL that contains the contents of the loaded stylesheet.
property syntax
syntax: Syntax;
The syntax with which to parse contents.
interface LegacyException
interface LegacyException extends Error {}
The exception type thrown by renderSync and passed as the error to render's callback.
Legacy
Deprecated
This is only thrown by the legacy render and renderSync APIs. Use compile, compileString, compileAsync, and compileStringAsync instead.
property column
column?: number;
The (1-based) column number within line at which the error occurred, if this exception is associated with a specific Sass file location.
property file
file?: string;
If this exception was caused by an error in a Sass file, this will represent the Sass file's location. It can be in one of three formats:
* If the Sass file was loaded from disk, this is the path to that file. * If the Sass file was generated by an importer, this is its canonical URL. * If the Sass file was passed as LegacyStringOptions.data without a corresponding LegacyStringOptions.file, this is the special string
"stdin"
.
property formatted
formatted: string;
property line
line?: number;
The (1-based) line number on which the error occurred, if this exception is associated with a specific Sass file location.
property message
message: string;
The error message. For Dart Sass, when possible this includes a highlighted indication of where in the source file the error occurred as well as the Sass stack trace.
property status
status: number;
Analogous to the exit code for an executable.
1
for an error caused by a Sass file,3
for any other type of error.
interface LegacyFileOptions
interface LegacyFileOptions<sync extends 'sync' | 'async'> extends LegacySharedOptions<sync> {}
property data
data?: never;
See LegacyStringOptions.file for documentation of passing file along with data.
Input
property file
file: string;
The path to the file for Sass to load and compile. If the file’s extension is
.scss
, it will be parsed as SCSS; if it’s.sass
, it will be parsed as the indented syntax; and if it’s.css
, it will be parsed as plain CSS. If it has no extension, it will be parsed as SCSS.Example 1
sass.renderSync({file: "style.scss"});Input feature: "Plain CSS files", dart: "1.11.0", node: "partial"
Node Sass and older versions of Dart Sass support loading files with the extension
.css
, but contrary to the specification they’re treated as SCSS files rather than being parsed as CSS. This behavior has been deprecated and should not be relied on. Any files that use Sass features should use the.scss
extension.All versions of Node Sass and Dart Sass otherwise support the file option as described below.
interface LegacyImporterThis
interface LegacyImporterThis extends LegacyPluginThis {}
The value of
this
in the context of a LegacyImporter function.Legacy
Deprecated
This is only used by the legacy render and renderSync APIs. Use Importer with compile, compileString, compileAsync, and compileStringAsync instead.
property fromImport
fromImport: boolean;
Whether the importer is being invoked because of a Sass
@import
rule, as opposed to a@use
or@forward
rule.This should *only* be used for determining whether or not to load [import-only files](https://sass-lang.com/documentation/at-rules/import#import-only-files).
dart: "1.33.0", node: false
interface LegacyPluginThis
interface LegacyPluginThis {}
The value of
this
in the context of a LegacyImporter or LegacyFunction callback.Legacy
Deprecated
This is only used by the legacy render and renderSync APIs. Use compile, compileString, compileAsync, and compileStringAsync instead.
property options
options: { /** The same {@link LegacyPluginThis} instance that contains this object. */ context: LegacyPluginThis;
/** * The value passed to {@link LegacyFileOptions.file} or {@link * LegacyStringOptions.file}. */ file?: string;
/** The value passed to {@link LegacyStringOptions.data}. */ data?: string;
/** * The value passed to {@link LegacySharedOptions.includePaths} separated by * `";"` on Windows or `":"` on other operating systems. This always * includes the current working directory as the first entry. */ includePaths: string;
/** Always the number 10. */ precision: 10;
/** Always the number 1. */ style: 1;
/** 1 if {@link LegacySharedOptions.indentType} was `"tab"`, 0 otherwise. */ indentType: 1 | 0;
/** * The value passed to {@link LegacySharedOptions.indentWidth}, or `2` * otherwise. */ indentWidth: number;
/** * The value passed to {@link LegacySharedOptions.linefeed}, or `"\n"` * otherwise. */ linefeed: '\r' | '\r\n' | '\n' | '\n\r';
/** A partially-constructed {@link LegacyResult} object. */ result: { /** Partial information about the compilation in progress. */ stats: { /** * The number of milliseconds between 1 January 1970 at 00:00:00 UTC and * the time at which Sass compilation began. */ start: number;
/** * {@link LegacyFileOptions.file} if it was passed, otherwise the string * `"data"`. */ entry: string; }; };};
A partial representation of the options passed to render or renderSync.
interface LegacyResult
interface LegacyResult {}
The object returned by render and renderSync after a successful compilation.
Legacy
Deprecated
This is only used by the legacy render and renderSync APIs. Use compile, compileString, compileAsync, and compileStringAsync instead.
property css
css: Buffer;
The compiled CSS. This can be converted to a string by calling [Buffer.toString](https://nodejs.org/api/buffer.html#buffer_buf_tostring_encoding_start_end).
Example 1
const result = sass.renderSync({file: "style.scss"});console.log(result.css.toString());
property map
map?: Buffer;
The source map that maps the compiled CSS to the source files from which it was generated. This can be converted to a string by calling [Buffer.toString](https://nodejs.org/api/buffer.html#buffer_buf_tostring_encoding_start_end).
This is
undefined
unless either* LegacySharedOptions.sourceMap is a string; or * LegacySharedOptions.sourceMap is
true
and LegacySharedOptions.outFile is set.The source map uses absolute [
file:
URLs](https://en.wikipedia.org/wiki/File_URI_scheme) to link to the Sass source files, except if the source file comes from LegacyStringOptions.data in which case it lists its URL as"stdin"
.Example 1
const result = sass.renderSync({file: "style.scss",sourceMap: true,outFile: "style.css"})console.log(result.map.toString());
property stats
stats: { /** * The absolute path of {@link LegacyFileOptions.file} or {@link * LegacyStringOptions.file}, or `"data"` if {@link * LegacyStringOptions.file} wasn't set. */ entry: string;
/** * The number of milliseconds between 1 January 1970 at 00:00:00 UTC and the * time at which Sass compilation began. */ start: number;
/** * The number of milliseconds between 1 January 1970 at 00:00:00 UTC and the * time at which Sass compilation ended. */ end: number;
/** * The number of milliseconds it took to compile the Sass file. This is * always equal to `start` minus `end`. */ duration: number;
/** * An array of the absolute paths of all Sass files loaded during * compilation. If a stylesheet was loaded from a {@link LegacyImporter} * that returned the stylesheet’s contents, the raw string of the `@use` or * `@import` that loaded that stylesheet included in this array. */ includedFiles: string[];};
Additional information about the compilation.
interface LegacySharedOptions
interface LegacySharedOptions<sync extends 'sync' | 'async'> {}
Options for render and renderSync that are shared between LegacyFileOptions and LegacyStringOptions.
Deprecated
This only works with the legacy render and renderSync APIs. Use Options with compile, compileString, compileAsync, and compileStringAsync instead.
property charset
charset?: boolean;
By default, if the CSS document contains non-ASCII characters, Sass adds a
@charset
declaration (in expanded output mode) or a byte-order mark (in compressed mode) to indicate its encoding to browsers or other consumers. Ifcharset
isfalse
, these annotations are omitted.Output dart: "1.39.0", node: false
property fatalDeprecations
fatalDeprecations?: (DeprecationOrId | Version)[];
A set of deprecations to treat as fatal.
If a deprecation warning of any provided type is encountered during compilation, the compiler will error instead.
If a
Version
is provided, then all deprecations that were active in that compiler version will be treated as fatal.Messages dart: "1.78.0", node: false
property functions
functions?: { [key: string]: LegacyFunction<sync> };
Additional built-in Sass functions that are available in all stylesheets. This option takes an object whose keys are Sass function signatures and whose values are LegacyFunctions. Each function should take the same arguments as its signature.
Functions are passed subclasses of LegacyValue, and must return the same.
**Heads up!** When writing custom functions, it’s important to ensure that all the arguments are the types you expect. Otherwise, users’ stylesheets could crash in hard-to-debug ways or, worse, compile to meaningless CSS.
Example 1
sass.render({data: `h1 {font-size: pow(2, 5) * 1px;}`,functions: {// This function uses the synchronous API, and can be passed to either// renderSync() or render().'pow($base, $exponent)': function(base, exponent) {if (!(base instanceof sass.types.Number)) {throw "$base: Expected a number.";} else if (base.getUnit()) {throw "$base: Expected a unitless number.";}if (!(exponent instanceof sass.types.Number)) {throw "$exponent: Expected a number.";} else if (exponent.getUnit()) {throw "$exponent: Expected a unitless number.";}return new sass.types.Number(Math.pow(base.getValue(), exponent.getValue()));},// This function uses the asynchronous API, and can only be passed to// render().'sqrt($number)': function(number, done) {if (!(number instanceof sass.types.Number)) {throw "$number: Expected a number.";} else if (number.getUnit()) {throw "$number: Expected a unitless number.";}done(new sass.types.Number(Math.sqrt(number.getValue())));}}}, function(err, result) {console.log(result.css.toString());// h1 {// font-size: 32px;// }});Plugins
property futureDeprecations
futureDeprecations?: DeprecationOrId[];
A set of future deprecations to opt into early.
Future deprecations passed here will be treated as active by the compiler, emitting warnings as necessary.
Messages dart: "1.78.0", node: false
property importer
importer?: LegacyImporter<sync> | LegacyImporter<sync>[];
Additional handler(s) for loading files when a [
@use
rule](https://sass-lang.com/documentation/at-rules/use) or an [@import
rule](https://sass-lang.com/documentation/at-rules/import) is encountered. It can either be a single LegacyImporter function, or an array of LegacyImporters.Importers take the URL of the
@import
or@use
rule and return a LegacyImporterResult indicating how to handle that rule. For more details, see LegacySyncImporter and LegacyAsyncImporter.Loads are resolved by trying, in order:
* Loading a file from disk relative to the file in which the
@use
or@import
appeared.* Each custom importer.
* Loading a file relative to the current working directory.
* Each load path in includePaths.
* Each load path specified in the
SASS_PATH
environment variable, which should be semicolon-separated on Windows and colon-separated elsewhere.Example 1
sass.render({file: "style.scss",importer: [// This importer uses the synchronous API, and can be passed to either// renderSync() or render().function(url, prev) {// This generates a stylesheet from scratch for `@use "big-headers"`.if (url != "big-headers") return null;return {contents: `h1 {font-size: 40px;}`};},// This importer uses the asynchronous API, and can only be passed to// render().function(url, prev, done) {// Convert `@use "foo/bar"` to "node_modules/foo/sass/bar".const components = url.split('/');const innerPath = components.slice(1).join('/');done({file: `node_modules/${components.first}/sass/${innerPath}`});}]}, function(err, result) {// ...});Plugins dart: true, node: "3.0.0"
Versions of Node Sass before 3.0.0 don’t support arrays of importers, nor do they support importers that return
Error
objects.Versions of Node Sass before 2.0.0 don’t support the
importer
option at all.feature: "Import order", dart: "1.20.2", node: false
Versions of Dart Sass before 1.20.2 preferred resolving imports using includePaths before resolving them using custom importers.
All versions of Node Sass currently pass imports to importers before loading them relative to the file in which the
@import
appears. This behavior is considered incorrect and should not be relied on because it violates the principle of *locality*, which says that it should be possible to reason about a stylesheet without knowing everything about how the entire system is set up. If a user tries to import a stylesheet relative to another stylesheet, that import should *always* work. It shouldn’t be possible for some configuration somewhere else to break it.
property includePaths
includePaths?: string[];
This array of strings option provides [load paths](https://sass-lang.com/documentation/at-rules/import#load-paths) for Sass to look for stylesheets. Earlier load paths will take precedence over later ones.
sass.renderSync({file: "style.scss",includePaths: ["node_modules/bootstrap/dist/css"]});Load paths are also loaded from the
SASS_PATH
environment variable, if it’s set. This variable should be a list of paths separated by;
(on Windows) or:
(on other operating systems). Load paths from theincludePaths
option take precedence over load paths fromSASS_PATH
.$ SASS_PATH=node_modules/bootstrap/dist/css sass style.scss style.cssInput feature: "SASS_PATH", dart: "1.15.0", node: "3.9.0"
Earlier versions of Dart Sass and Node Sass didn’t support the
SASS_PATH
environment variable.
property indentType
indentType?: 'space' | 'tab';
Whether the generated CSS should use spaces or tabs for indentation.
const result = sass.renderSync({file: "style.scss",indentType: "tab",indentWidth: 1});result.css.toString();// "h1 {\n\tfont-size: 40px;\n}\n"
property indentWidth
indentWidth?: number;
How many spaces or tabs (depending on indentType) should be used per indentation level in the generated CSS. It must be between 0 and 10 (inclusive).
property linefeed
linefeed?: 'cr' | 'crlf' | 'lf' | 'lfcr';
Which character sequence to use at the end of each line in the generated CSS. It can have the following values:
*
'lf'
uses U+000A LINE FEED. *'lfcr'
uses U+000A LINE FEED followed by U+000D CARRIAGE RETURN. *'cr'
uses U+000D CARRIAGE RETURN. *'crlf'
uses U+000D CARRIAGE RETURN followed by U+000A LINE FEED.
property logger
logger?: Logger;
An object to use to handle warnings and/or debug messages from Sass.
By default, Sass emits warnings and debug messages to standard error, but if Logger.warn or Logger.debug is set, this will invoke them instead.
The special value Logger.silent can be used to easily silence all messages.
Messages dart: "1.43.0", node: false
property omitSourceMapUrl
omitSourceMapUrl?: boolean;
If
true
, Sass won't add a link from the generated CSS to the source map.const result = sass.renderSync({file: "style.scss",sourceMap: "out.map",omitSourceMapUrl: true})console.log(result.css.toString());// h1 {// font-size: 40px;// }
property outFile
outFile?: string;
The location that Sass expects the generated CSS to be saved to. It’s used to determine the URL used to link from the generated CSS to the source map, and from the source map to the Sass source files.
**Heads up!** Despite the name, Sass does *not* write the CSS output to this file. The caller must do that themselves.
result = sass.renderSync({file: "style.scss",sourceMap: true,outFile: "out.css"})console.log(result.css.toString());// h1 {// font-size: 40px;// }// /*# sourceMappingURL=out.css.map * /Source Maps
property outputStyle
outputStyle?: 'compressed' | 'expanded' | 'nested' | 'compact';
The output style of the compiled CSS. There are four possible output styles:
*
"expanded"
(the default for Dart Sass) writes each selector and declaration on its own line.*
"compressed"
removes as many extra characters as possible, and writes the entire stylesheet on a single line.*
"nested"
(the default for Node Sass, not supported by Dart Sass) indents CSS rules to match the nesting of the Sass source.*
"compact"
(not supported by Dart Sass) puts each CSS rule on its own single line.Example 1
const source = `h1 {font-size: 40px;code {font-face: Roboto Mono;}}`;let result = sass.renderSync({data: source,outputStyle: "expanded"});console.log(result.css.toString());// h1 {// font-size: 40px;// }// h1 code {// font-face: Roboto Mono;// }result = sass.renderSync({data: source,outputStyle: "compressed"});console.log(result.css.toString());// h1{font-size:40px}h1 code{font-face:Roboto Mono}result = sass.renderSync({data: source,outputStyle: "nested"});console.log(result.css.toString());// h1 {// font-size: 40px; }// h1 code {// font-face: Roboto Mono; }result = sass.renderSync({data: source,outputStyle: "compact"});console.log(result.css.toString());// h1 { font-size: 40px; }// h1 code { font-face: Roboto Mono; }Output
property pkgImporter
pkgImporter?: NodePackageImporter;
If this option is set to an instance of
NodePackageImporter
, Sass will use the built-in Node.js package importer to resolve Sass files with apkg:
URL scheme. Details for library authors and users can be found in the NodePackageImporter documentation.Example 1
sass.renderSync({data: '@use "pkg:vuetify";',pkgImporter: new sass.NodePackageImporter()});Plugins dart: "2.0", node: false
property quietDeps
quietDeps?: boolean;
If this option is set to
true
, Sass won’t print warnings that are caused by dependencies. A “dependency” is defined as any file that’s loaded through includePaths or importer. Stylesheets that are imported relative to the entrypoint are not considered dependencies.This is useful for silencing deprecation warnings that you can’t fix on your own. However, please also notify your dependencies of the deprecations so that they can get fixed as soon as possible!
**Heads up!** If render or renderSync is called without LegacyFileOptions.file or LegacyStringOptions.file, all stylesheets it loads will be considered dependencies. Since it doesn’t have a path of its own, everything it loads is coming from a load path rather than a relative import.
property silenceDeprecations
silenceDeprecations?: DeprecationOrId[];
A set of active deprecations to ignore.
If a deprecation warning of any provided type is encountered during compilation, the compiler will ignore it instead.
**Heads up!** The deprecated functionality you're depending on will eventually break.
Messages dart: "1.78.0", node: false
property sourceMap
sourceMap?: boolean | string;
Whether or not Sass should generate a source map. If it does, the source map will be available as LegacyResult.map (unless sourceMapEmbed is
true
).If this option is a string, it’s the path that the source map is expected to be written to, which is used to link to the source map from the generated CSS and to link *from* the source map to the Sass source files. Note that if
sourceMap
is a string and outFile isn’t passed, Sass assumes that the CSS will be written to the same directory as the file option if it’s passed.If this option is
true
, the path is assumed to be outFile with.map
added to the end. If it’strue
and outFile isn’t passed, it has no effect.Example 1
let result = sass.renderSync({file: "style.scss",sourceMap: "out.map"})console.log(result.css.toString());// h1 {// font-size: 40px;// }// /*# sourceMappingURL=out.map * /result = sass.renderSync({file: "style.scss",sourceMap: true,outFile: "out.css"})console.log(result.css.toString());// h1 {// font-size: 40px;// }// /*# sourceMappingURL=out.css.map * /
property sourceMapContents
sourceMapContents?: boolean;
Whether to embed the entire contents of the Sass files that contributed to the generated CSS in the source map. This may produce very large source maps, but it guarantees that the source will be available on any computer no matter how the CSS is served.
Example 1
sass.renderSync({file: "style.scss",sourceMap: "out.map",sourceMapContents: true})
property sourceMapEmbed
sourceMapEmbed?: boolean;
Whether to embed the contents of the source map file in the generated CSS, rather than creating a separate file and linking to it from the CSS.
Example 1
sass.renderSync({file: "style.scss",sourceMap: "out.map",sourceMapEmbed: true});
property sourceMapRoot
sourceMapRoot?: string;
If this is passed, it's prepended to all the links from the source map to the Sass source files.
Source Maps
property verbose
verbose?: boolean;
By default, Dart Sass will print only five instances of the same deprecation warning per compilation to avoid deluging users in console noise. If you set
verbose
totrue
, it will instead print every deprecation warning it encounters.
interface LegacyStringOptions
interface LegacyStringOptions<sync extends 'sync' | 'async'> extends LegacySharedOptions<sync> {}
If data is passed, Sass will use it as the contents of the stylesheet to compile.
Deprecated
This only works with the legacy render and renderSync APIs. Use StringOptions with compile, compileString, compileAsync, and compileStringAsync instead.
property data
data: string;
The contents of the stylesheet to compile. Unless file is passed as well, the stylesheet’s URL is set to
"stdin"
.By default, this stylesheet is parsed as SCSS. This can be controlled using indentedSyntax.
Example 1
sass.renderSync({data: `h1 {font-size: 40px;}`});Input
property file
file?: string;
property indentedSyntax
indentedSyntax?: boolean;
This flag controls whether data is parsed as the indented syntax or not.
Example 1
sass.renderSync({data: `h1font-size: 40px`,indentedSyntax: true});
interface Logger
interface Logger {}
An object that can be passed to LegacySharedOptions.logger to control how Sass emits warnings and debug messages.
Example 1
const fs = require('fs');const sass = require('sass');let log = "";sass.renderSync({file: 'input.scss',logger: {warn(message, options) {if (options.span) {log += `${span.url}:${span.start.line}:${span.start.column}: ` +`${message}\n`;} else {log += `::: ${message}\n`;}}}});fs.writeFileSync('log.txt', log);Logger
method debug
debug: (message: string, options: { span: SourceSpan }) => void;
This method is called when Sass emits a debug message due to a [
@debug
rule](https://sass-lang.com/documentation/at-rules/debug).If this is
undefined
, Sass will print debug messages to standard error.Parameter message
The debug message.
Parameter
options.span - The location in the Sass source code that generated this debug message.
method warn
warn: (message: string, options: LoggerWarnOptions) => void;
This method is called when Sass emits a warning, whether due to a [
@warn
rule](https://sass-lang.com/documentation/at-rules/warn) or a warning generated by the Sass compiler.If this is
undefined
, Sass will print warnings to standard error.options
may contain the following fields:Parameter message
The warning message.
interface Options
interface Options<sync extends 'sync' | 'async'> {}
Options that can be passed to compile, compileAsync, compileString, or compileStringAsync.
property alertAscii
alertAscii?: boolean;
If this is
true
, the compiler will exclusively use ASCII characters in its error and warning messages. Otherwise, it may use non-ASCII Unicode characters as well.
property alertColor
alertColor?: boolean;
If this is
true
, the compiler will use ANSI color escape codes in its error and warning messages. If it'sfalse
, it won't use these. If it's undefined, the compiler will determine whether or not to use colors depending on whether the user is using an interactive terminal.Messages
property charset
charset?: boolean;
If
true
, the compiler may prepend@charset "UTF-8";
or U+FEFF (byte-order marker) if it outputs non-ASCII CSS.If
false
, the compiler never emits these byte sequences. This is ideal when concatenating or embedding in HTML<style>
tags. (The output will still be UTF-8.)
property fatalDeprecations
fatalDeprecations?: (DeprecationOrId | Version)[];
A set of deprecations to treat as fatal.
If a deprecation warning of any provided type is encountered during compilation, the compiler will error instead.
If a
Version
is provided, then all deprecations that were active in that compiler version will be treated as fatal.Messages dart: "1.74.0", node: false
property functions
functions?: Record<string, CustomFunction<sync>>;
Additional built-in Sass functions that are available in all stylesheets. This option takes an object whose keys are Sass function signatures like you'd write for the [`@function rule`](https://sass-lang.com/documentation/at-rules/function) and whose values are CustomFunctions.
Functions are passed subclasses of Value, and must return the same. If the return value includes SassCalculations they will be simplified before being returned.
When writing custom functions, it's important to make them as user-friendly and as close to the standards set by Sass's core functions as possible. Some good guidelines to follow include:
* Use
Value.assert*
methods, like Value.assertString, to cast untypedValue
objects to more specific types. For values that were passed directly as arguments, pass in the argument name as well. This ensures that the user gets good error messages when they pass in the wrong type to your function.* Individual classes may have more specific
assert*
methods, like SassNumber.assertInt, which should be used when possible.* In Sass, every value counts as a list. Rather than trying to detect the SassList type, you should use Value.asList to treat all values as lists.
* When manipulating values like lists, strings, and numbers that have metadata (comma versus space separated, bracketed versus unbracketed, quoted versus unquoted, units), the output metadata should match the input metadata.
* When in doubt, lists should default to comma-separated, strings should default to quoted, and numbers should default to unitless.
* In Sass, lists and strings use one-based indexing and use negative indices to index from the end of value. Functions should follow these conventions. Value.sassIndexToListIndex and SassString.sassIndexToStringIndex can be used to do this automatically.
* String indexes in Sass refer to Unicode code points while JavaScript string indices refer to UTF-16 code units. For example, the character U+1F60A SMILING FACE WITH SMILING EYES is a single Unicode code point but is represented in UTF-16 as two code units (
0xD83D
and0xDE0A
). So in JavaScript,"a😊b".charCodeAt(1)
returns0xD83D
, whereas in Sassstr-slice("a😊b", 1, 1)
returns"😊"
. Functions should follow Sass's convention. SassString.sassIndexToStringIndex can be used to do this automatically, and the SassString.sassLength getter can be used to access a string's length in code points.Example 1
sass.compileString(`h1 {font-size: pow(2, 5) * 1px;}`, {functions: {// Note: in real code, you should use `math.pow()` from the built-in// `sass:math` module.'pow($base, $exponent)': function(args) {const base = args[0].assertNumber('base').assertNoUnits('base');const exponent =args[1].assertNumber('exponent').assertNoUnits('exponent');return new sass.SassNumber(Math.pow(base.value, exponent.value));}}});Plugins
property futureDeprecations
futureDeprecations?: DeprecationOrId[];
A set of future deprecations to opt into early.
Future deprecations passed here will be treated as active by the compiler, emitting warnings as necessary.
Messages dart: "1.74.0", node: false
property importers
importers?: (Importer<sync> | FileImporter<sync> | NodePackageImporter)[];
Custom importers that control how Sass resolves loads from rules like [
@use
](https://sass-lang.com/documentation/at-rules/use) and [@import
](https://sass-lang.com/documentation/at-rules/import).Loads are resolved by trying, in order:
- The importer that was used to load the current stylesheet, with the loaded URL resolved relative to the current stylesheet's canonical URL.
- Each Importer, FileImporter, or NodePackageImporter in importers, in order.
- Each load path in loadPaths, in order.
If none of these return a Sass file, the load fails and Sass throws an error.
Plugins
property loadPaths
loadPaths?: string[];
Paths in which to look for stylesheets loaded by rules like [
@use
](https://sass-lang.com/documentation/at-rules/use) and [@import
](https://sass-lang.com/documentation/at-rules/import).A load path
loadPath
is equivalent to the following FileImporter:{findFileUrl(url) {// Load paths only support relative URLs.if (/^[a-z]+:/i.test(url)) return null;return new URL(url, pathToFileURL(loadPath));}}Input
property logger
logger?: Logger;
An object to use to handle warnings and/or debug messages from Sass.
By default, Sass emits warnings and debug messages to standard error, but if Logger.warn or Logger.debug is set, this will invoke them instead.
The special value Logger.silent can be used to easily silence all messages.
Messages
property quietDeps
quietDeps?: boolean;
If this option is set to
true
, Sass won’t print warnings that are caused by dependencies. A “dependency” is defined as any file that’s loaded through loadPaths or importers. Stylesheets that are imported relative to the entrypoint are not considered dependencies.This is useful for silencing deprecation warnings that you can’t fix on your own. However, please also notify your dependencies of the deprecations so that they can get fixed as soon as possible!
**Heads up!** If compileString or compileStringAsync is called without StringOptions.url, all stylesheets it loads will be considered dependencies. Since it doesn’t have a path of its own, everything it loads is coming from a load path rather than a relative import.
property silenceDeprecations
silenceDeprecations?: DeprecationOrId[];
A set of active deprecations to ignore.
If a deprecation warning of any provided type is encountered during compilation, the compiler will ignore it instead.
**Heads up!** The deprecated functionality you're depending on will eventually break.
Messages dart: "1.74.0", node: false
property sourceMap
sourceMap?: boolean;
Whether or not Sass should generate a source map. If it does, the source map will be available as CompileResult.sourceMap.
**Heads up!** Sass doesn't automatically add a
sourceMappingURL
comment to the generated CSS. It's up to callers to do that, since callers have full knowledge of where the CSS and the source map will exist in relation to one another and how they'll be served to the browser.
property sourceMapIncludeSources
sourceMapIncludeSources?: boolean;
Whether Sass should include the sources in the generated source map.
This option has no effect if sourceMap is
false
.
property style
style?: OutputStyle;
The OutputStyle of the compiled CSS.
Example 1
const source = `h1 {font-size: 40px;code {font-face: Roboto Mono;}}`;let result = sass.compileString(source, {style: "expanded"});console.log(result.css.toString());// h1 {// font-size: 40px;// }// h1 code {// font-face: Roboto Mono;// }result = sass.compileString(source, {style: "compressed"})console.log(result.css.toString());// h1{font-size:40px}h1 code{font-face:Roboto Mono}Output
property verbose
verbose?: boolean;
By default, Dart Sass will print only five instances of the same deprecation warning per compilation to avoid deluging users in console noise. If you set
verbose
totrue
, it will instead print every deprecation warning it encounters.
interface SourceLocation
interface SourceLocation {}
A specific location within a source file.
This is always associated with a SourceSpan which indicates *which* file it refers to.
Logger
interface SourceSpan
interface SourceSpan {}
A span of text within a source file.
Logger
property context
context?: string;
Text surrounding the span.
If this is set, it must include only whole lines, and it must include at least all line(s) which are partially covered by this span.
property end
end: SourceLocation;
property start
start: SourceLocation;
The beginning of this span, inclusive.
property text
text: string;
The text covered by the span.
property url
url?: URL;
The canonical URL of the file this span refers to.
interface StringOptions
interface StringOptions<sync extends 'sync' | 'async'> extends Options<sync> {}
Options that can be passed to compileString or compileStringAsync.
If the StringOptions.importer field isn't passed, the entrypoint file can load files relative to itself if a
file://
URL is passed to the url field. If it is passed, the entrypoint file uses it to load files relative to itself.
property importer
importer?: Importer<sync> | FileImporter<sync>;
property syntax
syntax?: Syntax;
The Syntax to use to parse the entrypoint stylesheet.
'scss'
Input
property url
url?: URL;
The canonical URL of the entrypoint stylesheet.
A relative load's URL is first resolved relative to url, then resolved to a file on disk if it's a
file://
URL. If it can't be resolved to a file on disk, it's then passed to importers and loadPaths.Input feature: "Undefined URL with importer", dart: "1.75.0", node: false
Earlier versions of Dart Sass required url to be defined when passing StringOptions.importer.
Type Aliases
type CalculationOperator
type CalculationOperator = '+' | '-' | '*' | '/';
The set of possible operators in a Sass calculation. Custom Function
type CalculationValue
type CalculationValue = | SassNumber | SassCalculation | SassString | CalculationOperation | CalculationInterpolation;
The type of values that can be arguments to a SassCalculation. Custom Function
type ChannelName
type ChannelName = | ChannelNameHsl | ChannelNameHwb | ChannelNameLab | ChannelNameLch | ChannelNameRgb | ChannelNameXyz;
All supported color space channel names.
type ChannelNameHsl
type ChannelNameHsl = 'hue' | 'saturation' | 'lightness' | 'alpha';
The HSL color space channel names.
type ChannelNameHwb
type ChannelNameHwb = 'hue' | 'whiteness' | 'blackness' | 'alpha';
The HWB color space channel names.
type ChannelNameLab
type ChannelNameLab = 'lightness' | 'a' | 'b' | 'alpha';
The Lab / Oklab color space channel names.
type ChannelNameLch
type ChannelNameLch = 'lightness' | 'chroma' | 'hue' | 'alpha';
The LCH / Oklch color space channel names.
type ChannelNameRgb
type ChannelNameRgb = 'red' | 'green' | 'blue' | 'alpha';
RGB channel names.
type ChannelNameXyz
type ChannelNameXyz = 'x' | 'y' | 'z' | 'alpha';
XYZ channel names.
type ColorSpaceHsl
type ColorSpaceHsl = 'hsl';
The HSL color space name.
type ColorSpaceHwb
type ColorSpaceHwb = 'hwb';
The HWB color space name.
type ColorSpaceLab
type ColorSpaceLab = 'lab' | 'oklab';
The Lab / Oklab color space names.
type ColorSpaceLch
type ColorSpaceLch = 'lch' | 'oklch';
The LCH / Oklch color space names.
type ColorSpaceRgb
type ColorSpaceRgb = | 'a98-rgb' | 'display-p3' | 'prophoto-rgb' | 'rec2020' | 'rgb' | 'srgb' | 'srgb-linear';
Names of color spaces with RGB channels.
type ColorSpaceXyz
type ColorSpaceXyz = 'xyz' | 'xyz-d50' | 'xyz-d65';
Names of color spaces with XYZ channels.
type CustomFunction
type CustomFunction<sync extends 'sync' | 'async'> = ( args: Value[]) => PromiseOr<Value, sync>;
A callback that implements a custom Sass function. This can be passed to Options.functions.
const result = sass.compile('style.scss', {functions: {"sum($arg1, $arg2)": (args) => {const arg1 = args[0].assertNumber('arg1');const value1 = arg1.value;const value2 = args[1].assertNumber('arg2').convertValueToMatch(arg1, 'arg2', 'arg1');return new sass.SassNumber(value1 + value2).coerceToMatch(arg1);}}});Parameter args
An array of arguments passed by the function's caller. If the function takes [arbitrary arguments](https://sass-lang.com/documentation/at-rules/function#taking-arbitrary-arguments), the last element will be a SassArgumentList.
Returns
The function's result. This may be in the form of a
Promise
, but if it is the function may only be passed to compileAsync and compileStringAsync, not compile or compileString.Throws
any - This function may throw an error, which the Sass compiler will treat as the function call failing. If the exception object has a
message
property, it will be used as the wrapped exception's message; otherwise, the exception object'stoString()
will be used. This means it's safe for custom functions to throw plain strings.Custom Function
type DeprecationOrId
type DeprecationOrId = Deprecation | keyof Deprecations;
Either a deprecation or its ID, either of which can be passed to any of the relevant compiler options.
Messages dart: "1.74.0", node: false
type DeprecationStatus
type DeprecationStatus = 'active' | 'user' | 'future' | 'obsolete';
The possible statuses that each deprecation can have.
"active" deprecations are currently emitting deprecation warnings. "future" deprecations are not yet active, but will be in the future. "obsolete" deprecations were once active, but no longer are.
The only "user" deprecation is "user-authored", which is used for deprecation warnings coming from user code.
Messages dart: "1.74.0", node: false
type GamutMapMethod
type GamutMapMethod = 'clip' | 'local-minde';
Methods by which colors in bounded spaces can be mapped to within their gamut.
*
local-minde
: The algorithm specified in [the original Color Level 4 candidate recommendation]. This maps in the Oklch color space, using the [deltaEOK] color difference formula and the [local-MINDE] improvement.*
clip
: Clamp each color channel that's outside the gamut to the minimum or maximum value for that channel. This algorithm will produce poor visual results, but it may be useful to match the behavior of other situations in which a color can be clipped.[the original Color Level 4 candidate recommendation]: https://www.w3.org/TR/2024/CRD-css-color-4-20240213/#css-gamut-mapping [deltaEOK]: https://www.w3.org/TR/2024/CRD-css-color-4-20240213/#color-difference-OK [local-MINDE]: https://www.w3.org/TR/2024/CRD-css-color-4-20240213/#GM-chroma-local-MINDE
type HueInterpolationMethod
type HueInterpolationMethod = 'decreasing' | 'increasing' | 'longer' | 'shorter';
Methods by which two hues are adjusted when interpolating between polar colors.
type KnownColorSpace
type KnownColorSpace = | ColorSpaceHsl | ColorSpaceHwb | ColorSpaceLab | ColorSpaceLch | ColorSpaceRgb | ColorSpaceXyz;
All supported color space names.
type LegacyAsyncFunction
type LegacyAsyncFunction = | ((this: LegacyPluginThis, done: (result: LegacyValue) => void) => void) | (( this: LegacyPluginThis, arg1: LegacyValue, done: LegacyAsyncFunctionDone ) => void) | (( this: LegacyPluginThis, arg1: LegacyValue, arg2: LegacyValue, done: LegacyAsyncFunctionDone ) => void) | (( this: LegacyPluginThis, arg1: LegacyValue, arg2: LegacyValue, arg3: LegacyValue, done: LegacyAsyncFunctionDone ) => void) | (( this: LegacyPluginThis, arg1: LegacyValue, arg2: LegacyValue, arg3: LegacyValue, arg4: LegacyValue, done: LegacyAsyncFunctionDone ) => void) | (( this: LegacyPluginThis, arg1: LegacyValue, arg2: LegacyValue, arg3: LegacyValue, arg4: LegacyValue, arg5: LegacyValue, done: LegacyAsyncFunctionDone ) => void) | (( this: LegacyPluginThis, arg1: LegacyValue, arg2: LegacyValue, arg3: LegacyValue, arg4: LegacyValue, arg5: LegacyValue, arg6: LegacyValue, done: LegacyAsyncFunctionDone ) => void) | (( this: LegacyPluginThis, ...args: [...LegacyValue[], LegacyAsyncFunctionDone] ) => void);
An asynchronous callback that implements a custom Sass function. This can be passed to LegacySharedOptions.functions, but only for render.
An asynchronous function must return
undefined
. Its final argument will always be a callback, which it should call with the result of the function once it's done running.If this throws an error, Sass will treat that as the function failing with that error message.
sass.render({file: 'style.scss',functions: {"sum($arg1, $arg2)": (arg1, arg2, done) => {if (!(arg1 instanceof sass.types.Number)) {throw new Error("$arg1: Expected a number");} else if (!(arg2 instanceof sass.types.Number)) {throw new Error("$arg2: Expected a number");}done(new sass.types.Number(arg1.getValue() + arg2.getValue()));}}}, (result, error) => {// ...});This is passed one argument for each argument that's declared in the signature that's passed to LegacySharedOptions.functions. If the signature [takes arbitrary arguments](https://sass-lang.com/documentation/at-rules/function#taking-arbitrary-arguments), they're passed as a single argument list in the last argument before the callback.
Legacy
Deprecated
This only works with the legacy render and renderSync APIs. Use CustomFunction with compile, compileString, compileAsync, and compileStringAsync instead.
type LegacyAsyncFunctionDone
type LegacyAsyncFunctionDone = (result: LegacyValue | types.Error) => void;
The function called by a LegacyAsyncFunction to indicate that it's finished.
Parameter result
If this is a LegacyValue, that indicates that the function call completed successfully. If it's a types.Error, that indicates that the function call failed.
Legacy
Deprecated
This only works with the legacy render and renderSync APIs. Use CustomFunction with compile, compileString, compileAsync, and compileStringAsync instead.
type LegacyAsyncImporter
type LegacyAsyncImporter = ( this: LegacyImporterThis, url: string, prev: string, done: (result: LegacyImporterResult) => void) => void;
An asynchronous callback that implements custom Sass loading logic for [
@import
rules](https://sass-lang.com/documentation/at-rules/import) and [@use
rules](https://sass-lang.com/documentation/at-rules/use). This can be passed to LegacySharedOptions.importer for either render or renderSync.An asynchronous importer must return
undefined
, and then calldone
with the result of its LegacyImporterResult once it's done running.See LegacySharedOptions.importer for more detailed documentation.
sass.render({file: "style.scss",importer: [function(url, prev, done) {if (url != "big-headers") done(null);done({contents: 'h1 { font-size: 40px; }'});}]});Parameter url
The
@use
or@import
rule’s URL as a string, exactly as it appears in the stylesheet.Parameter prev
A string identifying the stylesheet that contained the
@use
or@import
. This string’s format depends on how that stylesheet was loaded:* If the stylesheet was loaded from the filesystem, it’s the absolute path of its file. * If the stylesheet was loaded from an importer that returned its contents, it’s the URL of the
@use
or@import
rule that loaded it. * If the stylesheet came from the data option, it’s the string "stdin".Parameter done
The callback to call once the importer has finished running.
Legacy
Deprecated
This only works with the legacy render and renderSync APIs. Use Importer with compile, compileString, compileAsync, and compileStringAsync instead.
type LegacyFunction
type LegacyFunction<sync extends 'sync' | 'async'> = sync extends 'async' ? LegacySyncFunction | LegacyAsyncFunction : LegacySyncFunction;
A callback that implements a custom Sass function. For renderSync, this must be a LegacySyncFunction which returns its result directly; for render, it may be either a LegacySyncFunction or a LegacyAsyncFunction which calls a callback with its result.
See LegacySharedOptions.functions for more details.
Legacy
Deprecated
This only works with the legacy render and renderSync APIs. Use CustomFunction with compile, compileString, compileAsync, and compileStringAsync instead.
type LegacyImporter
type LegacyImporter<sync = 'sync' | 'async'> = sync extends 'async' ? LegacySyncImporter | LegacyAsyncImporter : LegacySyncImporter;
A callback that implements custom Sass loading logic for [
@import
rules](https://sass-lang.com/documentation/at-rules/import) and [@use
rules](https://sass-lang.com/documentation/at-rules/use). For renderSync, this must be a LegacySyncImporter which returns its result directly; for render, it may be either a LegacySyncImporter or a LegacyAsyncImporter which calls a callback with its result.See LegacySharedOptions.importer for more details.
Legacy
Deprecated
This only works with the legacy render and renderSync APIs. Use Importer with compile, compileString, compileAsync, and compileStringAsync instead.
type LegacyImporterResult
type LegacyImporterResult = { file: string } | { contents: string } | Error | null;
The result of running a LegacyImporter. It must be one of the following types:
* An object with the key
contents
whose value is the contents of a stylesheet (in SCSS syntax). This causes Sass to load that stylesheet’s contents.* An object with the key
file
whose value is a path on disk. This causes Sass to load that file as though it had been imported directly.*
null
, which indicates that it doesn’t recognize the URL and another importer should be tried instead.* An [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, indicating that importing failed.
Legacy
Deprecated
This only works with the legacy render and renderSync APIs. Use ImporterResult with compile, compileString, compileAsync, and compileStringAsync instead.
type LegacyOptions
type LegacyOptions<sync extends 'sync' | 'async'> = | LegacyFileOptions<sync> | LegacyStringOptions<sync>;
Options for render and renderSync. This can either be LegacyFileOptions to load a file from disk, or LegacyStringOptions to compile a string of Sass code.
See LegacySharedOptions for options that are shared across both file and string inputs.
Legacy
Deprecated
This only works with the legacy render and renderSync APIs. Use Options with compile, compileString, compileAsync, and compileStringAsync instead.
type LegacySyncFunction
type LegacySyncFunction = ( this: LegacyPluginThis, ...args: LegacyValue[]) => LegacyValue;
A synchronous callback that implements a custom Sass function. This can be passed to LegacySharedOptions.functions for either render or renderSync.
If this throws an error, Sass will treat that as the function failing with that error message.
const result = sass.renderSync({file: 'style.scss',functions: {"sum($arg1, $arg2)": (arg1, arg2) => {if (!(arg1 instanceof sass.types.Number)) {throw new Error("$arg1: Expected a number");} else if (!(arg2 instanceof sass.types.Number)) {throw new Error("$arg2: Expected a number");}return new sass.types.Number(arg1.getValue() + arg2.getValue());}}});Parameter args
One argument for each argument that's declared in the signature that's passed to LegacySharedOptions.functions. If the signature [takes arbitrary arguments](https://sass-lang.com/documentation/at-rules/function#taking-arbitrary-arguments), they're passed as a single argument list in the last argument.
Legacy
Deprecated
This only works with the legacy render and renderSync APIs. Use CustomFunction with compile, compileString, compileAsync, and compileStringAsync instead.
type LegacySyncImporter
type LegacySyncImporter = ( this: LegacyImporterThis, url: string, prev: string) => LegacyImporterResult;
A synchronous callback that implements custom Sass loading logic for [
@import
rules](https://sass-lang.com/documentation/at-rules/import) and [@use
rules](https://sass-lang.com/documentation/at-rules/use). This can be passed to LegacySharedOptions.importer for either render or renderSync.See LegacySharedOptions.importer for more detailed documentation.
sass.renderSync({file: "style.scss",importer: [function(url, prev) {if (url != "big-headers") return null;return {contents: 'h1 { font-size: 40px; }'};}]});Parameter url
The
@use
or@import
rule’s URL as a string, exactly as it appears in the stylesheet.Parameter prev
A string identifying the stylesheet that contained the
@use
or@import
. This string’s format depends on how that stylesheet was loaded:* If the stylesheet was loaded from the filesystem, it’s the absolute path of its file. * If the stylesheet was loaded from an importer that returned its contents, it’s the URL of the
@use
or@import
rule that loaded it. * If the stylesheet came from the data option, it’s the string "stdin".Legacy
Deprecated
This only works with the legacy render and renderSync APIs. Use Importer with compile, compileString, compileAsync, and compileStringAsync instead.
type LegacyValue
type LegacyValue = | types.Null | types.Number | types.String | types.Boolean | types.Color | types.List | types.Map;
A type representing all the possible values that may be passed to or returned from a LegacyFunction.
Legacy
Deprecated
This only works with the legacy render and renderSync APIs. Use Value with compile, compileString, compileAsync, and compileStringAsync instead.
type ListSeparator
type ListSeparator = ',' | '/' | ' ' | null;
Possible separators used by Sass lists. The special separator
null
is only used for lists with fewer than two elements, and indicates that the separator has not yet been decided for this list.Custom Function
type LoggerWarnOptions
type LoggerWarnOptions = ( | { deprecation: true; deprecationType: Deprecation; } | { deprecation: false }) & { span?: SourceSpan; stack?: string;};
The options passed to Logger.warn.
*
deprecation
: Whether this is a deprecation warning.*
deprecationType
: The type of deprecation. Only set ifdeprecation
is true.*
span
: The location in the Sass source code that generated this warning. This may be unset if the warning didn't come from Sass source, for example if it's from a deprecated JavaScript option.*
stack
: The Sass stack trace at the point the warning was issued. This may be unset if the warning didn't come from Sass source, for example if it's from a deprecated JavaScript option.Logger
type OutputStyle
type OutputStyle = 'expanded' | 'compressed';
Possible output styles for the compiled CSS:
-
"expanded"
(the default for Dart Sass) writes each selector and declaration on its own line.-
"compressed"
removes as many extra characters as possible, and writes the entire stylesheet on a single line.Options
type PolarColorSpace
type PolarColorSpace = ColorSpaceHsl | ColorSpaceHwb | ColorSpaceLch;
Polar color space names (HSL, HWB, LCH, and Oklch spaces).
type PromiseOr
type PromiseOr<T, sync extends 'sync' | 'async'> = sync extends 'async' ? T | Promise<T> : T;
A utility type for choosing between synchronous and asynchronous return values.
This is used as the return value for plugins like CustomFunction, Importer, and FileImporter so that TypeScript enforces that asynchronous plugins are only passed to compileAsync and compileStringAsync, not compile or compileString.
type RectangularColorSpace
type RectangularColorSpace = Exclude<KnownColorSpace, PolarColorSpace>;
Rectangular color space names (Lab, Oklab, RGB, and XYZ spaces).
type StringOptionsWithImporter
type StringOptionsWithImporter<sync extends 'sync' | 'async'> = StringOptions<sync>;
Options
Deprecated
Use StringOptions instead.
type StringOptionsWithoutImporter
type StringOptionsWithoutImporter<sync extends 'sync' | 'async'> = StringOptions<sync>;
Options
Deprecated
Use StringOptions instead.
type Syntax
type Syntax = 'scss' | 'indented' | 'css';
Syntaxes supported by Sass:
-
'scss'
is the [SCSS syntax](https://sass-lang.com/documentation/syntax#scss). -'indented'
is the [indented syntax](https://sass-lang.com/documentation/syntax#the-indented-syntax) -'css'
is plain CSS, which is parsed like SCSS but forbids the use of any special Sass features.Options
Namespaces
namespace Logger
namespace Logger {}
A namespace for built-in Loggers.
Logger dart: "1.43.0", node: false
namespace types
namespace types {}
The namespace for value types used in the legacy function API.
Legacy
Deprecated
This only works with the legacy render and renderSync APIs. Use Value with compile, compileString, compileAsync, and compileStringAsync instead.
class Boolean
class Boolean<T extends boolean = boolean> {}
Sass's [boolean type](https://sass-lang.com/documentation/values/booleans).
Custom functions should respect Sass’s notion of [truthiness](https://sass-lang.com/documentation/at-rules/control/if#truthiness-and-falsiness) by treating
false
andnull
as falsey and everything else as truthy.**Heads up!** Boolean values can't be constructed, they can only be accessed through the TRUE and FALSE constants.
property FALSE
static readonly FALSE: Boolean<false>;
Sass's
false
value.
property TRUE
static readonly TRUE: Boolean<true>;
Sass's
true
value.
method getValue
getValue: () => T;
Returns
true
if this is Sass'strue
value andfalse
if this is Sass'sfalse
value.Example 1
// boolean is `true`.boolean.getValue(); // trueboolean === sass.types.Boolean.TRUE; // true// boolean is `false`.boolean.getValue(); // falseboolean === sass.types.Boolean.FALSE; // true
class Color
class Color {}
Sass's [color type](https://sass-lang.com/documentation/values/colors).
constructor
constructor( r: globalThis.Number, g: globalThis.Number, b: globalThis.Number, a?: globalThis.Number);
Creates a new Sass color with the given red, green, blue, and alpha channels. The red, green, and blue channels must be integers between 0 and 255 (inclusive), and alpha must be between 0 and 1 (inclusive).
Example 1
new sass.types.Color(107, 113, 127); // #6b717fnew sass.types.Color(0, 0, 0, 0); // rgba(0, 0, 0, 0)
constructor
constructor(argb: globalThis.Number);
Creates a new Sass color with alpha, red, green, and blue channels taken from respective two-byte chunks of a hexidecimal number.
Example 1
new sass.types.Color(0xff6b717f); // #6b717fnew sass.types.Color(0x00000000); // rgba(0, 0, 0, 0)
method getA
getA: () => number;
Returns the alpha channel of the color as a number from 0 to 1.
Example 1
// color is `#6b717f`.color.getA(); // 1// color is `transparent`.color.getA(); // 0
method getB
getB: () => number;