NODE-SASS(1)

πŸ’– NODE-SASS πŸ’–

okay bestie, welcome to node-sass β€” the Node.js bindings to libsass. yes she's iconic, yes she compiles your .scss at ridiculous speed. let's get into it πŸŽ€


✨ NAME ✨

node-sass β€” Node.js bindings to libsass

🌸 Supported Node.js versions 🌸

okay so this is lowkey important β€” supported Node.js versions vary by release, so pls pls pls go consult the releases page at https://github.com/sass/node-sass/releases. but here's a quick guide for minimum support so you're not out here guessing:

  • Node 12 β†’ minimum node-sass version 4.12+, Node Module 72
  • Node 11 β†’ minimum node-sass version 4.10+, Node Module 67
  • Node 10 β†’ minimum node-sass version 4.9+, Node Module 64
  • Node 8 β†’ minimum node-sass version 4.5.3+, Node Module 57

(the original ships that as a lil box-drawn table and honestly? the vibe. anyway you have the numbers now πŸ’…)


πŸ¦‹ The badges section πŸ¦‹

okay this part is literally just her flex wall. the original has a <table> with two cells:

and then the badge roll call, fr fr:

main character energy, honestly πŸ‘‘


πŸ’œ DESCRIPTION πŸ’œ

so what IS she? Node-sass is a library that provides binding for Node.js to LibSass (https://github.com/sass/libsass) β€” that's the C version of the popular stylesheet preprocessor, Sass.

which means: it lets you natively compile .scss files to css at incredible speed and automatically via a connect middleware. literally the way that it just… does that. obsessed.

find it on npm: https://www.npmjs.com/package/node-sass

follow @nodesass on twitter for release updates: https://twitter.com/nodesass 🐦


πŸŽ€ INSTALL πŸŽ€

npm install node-sass

okay a couple of real ones before you start yelling at your terminal:

are you seeing the following error? check out our Troubleshooting guide at https://github.com/sass/node-sass/blob/master/TROUBLESHOOTING.md#installing-node-sass-4x-with-node--4.** shell SyntaxError: Use of const in strict mode.

having installation troubles? check out our Troubleshooting guide at https://github.com/sass/node-sass/blob/master/TROUBLESHOOTING.md. no cap, it's right there πŸ’€


🌈 Install from mirror in China 🌈

npm install -g mirror-config-china --registry=http://registry.npm.taobao.org
npm install node-sass

⭐ USAGE ⭐

here's the whole vibe, verbatim:

var sass = require('node-sass');
sass.render({
  file: scss_filename,
  [, options..]
}, function(err, result) { /*...*/ });
// OR
var result = sass.renderSync({
  data: scss_content
  [, options..]
});

yes bestie, render is async with a callback, renderSync just hands you the result straight up. pick your fighter πŸ’…

✨ OPTIONS ✨

  • file β€” okay so this is the path to a file for LibSass https://github.com/sass/libsass to compile. πŸ’…
    • Type: String
    • Default: null
    • Special: file or data must be specified β€” no cap, you gotta pick one bestie. 🫢
  • data β€” a string to pass to LibSass https://github.com/sass/libsass to compile. It's giving "I have a string and I'm not afraid to use it". ✨
    • Type: String
    • Default: null
    • Special: file or data must be specified β€” literally pick your fighter. πŸ’€
    • It is recommended that you use includePaths in conjunction with this so that LibSass https://github.com/sass/libsass can find files when using the @import directive. fr fr, don't skip this. πŸŽ€
  • importer (>= v2.0.0) - experimental β€” handles when LibSass https://github.com/sass/libsass encounters the @import directive. It's giving main character energy. πŸ‘‘
⚠️ This is an experimental LibSass feature. Use with caution. Lowkey risky, highkey powerful. πŸ’…
  • Type: Function | Function[] signature function(url, prev, done)
  • Default: undefined
  • Function Parameters and Information:
    • url (String) β€” the path in import as-is, which LibSass https://github.com/sass/libsass encountered
    • prev (String) β€” the previously resolved path
    • done (Function) β€” a callback function to invoke on async completion, takes an object literal containing
      • file (String) β€” an alternate path for LibSass https://github.com/sass/libsass to use OR
      • contents (String) β€” the imported contents (for example, read from memory or the file system)
  • Handles when LibSass https://github.com/sass/libsass encounters the @import directive. A custom importer allows extension of the LibSass https://github.com/sass/libsass engine in both a synchronous and asynchronous manner. In both cases, the goal is to either return or call done() with an object literal. Depending on the value of the object literal, one of two things will happen. πŸ‘€
  • When returning or calling done() with { file: "String" }, the new file path will be assumed for the @import. It's recommended to be mindful of the value of prev in instances where relative path resolution may be required. iykyk. 🧚
  • When returning or calling done() with { contents: "String" }, the string value will be used as if the file was read in through an external source. Slay. πŸ’–
  • Starting from v3.0.0:
    • this refers to a contextual scope for the immediate run of sass.render or sass.renderSync
    • importers can return error and LibSass will emit that error in response. For instance:
done(new Error('doesn\'t exist!'));
// or return synchronously
return new Error('nothing to do here');
  • importer can be an array of functions, which will be called by LibSass in the order of their occurrence in array. This helps user specify special importer for particular kind of path (filesystem, http). If an importer does not want to handle a particular path, it should return null. See functions section #functions--v300---experimental for more details on Sass types. πŸ¦‹
  • functions (>= v3.0.0) - experimental β€” an Object that holds a collection of custom functions that may be invoked by the sass files being compiled. It's giving "I can has custom functions?" 😭
⚠️ This is an experimental LibSass feature. Use with caution. No cap, it's giving experimental. πŸ§ͺ
  • functions is an Object that holds a collection of custom functions that may be invoked by the sass files being compiled. They may take zero or more input parameters and must return a value either synchronously (return ...;) or asynchronously (done();). Those parameters will be instances of one of the constructors contained in the require('node-sass').types hash. The return value must be of one of these types as well. See the list of available types below: πŸ‘‡
  • types.Number(value [, unit = ]) β€” the number type, bestie. It's giving math class. πŸ“
    • getValue() / setValue(value) β€” gets / sets the numerical portion of the number
    • getUnit() / setUnit(unit) β€” gets / sets the unit portion of the number
  • types.String(value) β€” the string type. It's giving text vibes. πŸ’¬
    • getValue() / setValue(value) β€” gets / sets the enclosed string
  • types.Color(r, g, b [, a = 1.0]) or types.Color(argb) β€” the color type. It's giving rainbow. 🌈
    • getR() / setR(value) β€” red component (integer from 0 to 255)
    • getG() / setG(value) β€” green component (integer from 0 to 255)
    • getB() / setB(value) β€” blue component (integer from 0 to 255)
    • getA() / setA(value) β€” alpha component (number from 0 to 1.0)
    • Example:
var Color = require('node-sass').types.Color,
  c1 = new Color(255, 0, 0),
  c2 = new Color(0xff0088cc);
  • types.Boolean(value) β€” the boolean type. It's giving true/false energy. βœ…
    • getValue() β€” gets the enclosed boolean
    • types.Boolean.TRUE β€” Singleton instance of types.Boolean that holds "true"
    • types.Boolean.FALSE β€” Singleton instance of types.Boolean that holds "false"
  • types.List(length [, commaSeparator = true]) β€” the list type. It's giving array but make it Sass. πŸ“‹
    • getValue(index) / setValue(index, value) β€” value must itself be an instance of one of the constructors in sass.types.
    • getSeparator() / setSeparator(isComma) β€” whether to use commas as a separator
    • getLength()
  • types.Map(length) β€” the map type. It's giving key-value realness. πŸ—ΊοΈ
    • getKey(index) / setKey(index, value)
    • getValue(index) / setValue(index, value)
    • getLength()
  • types.Null() β€” the null type. It's giving nothing but in a cute way. πŸ•³οΈ
    • types.Null.NULL β€” Singleton instance of types.Null.
  • Example:
sass.renderSync({
  data: '#{headings(2,5)} { color: #08c; }',
  functions: {
    'headings($from: 0, $to: 6)': function(from, to) {
      var i, f = from.getValue(), t = to.getValue(),
          list = new sass.types.List(t - f + 1);

      for (i = f; i <= t; i++) {
        list.setValue(i - f, new sass.types.String('h' + i));
      }

      return list;
    }
  }
});
  • includePaths β€” an array of paths that LibSass https://github.com/sass/libsass can look in to attempt to resolve your @import declarations. When using data, it is recommended that you use this. Periodt. πŸ’…
    • Type: Array<String>
    • Default: []
  • indentedSyntax β€” true values enable Sass Indented Syntax https://sass-lang.com/documentation/file.INDENTED_SYNTAX.html for parsing the data string or file. It's giving old school but make it cute. πŸŽ€
    • Type: Boolean
    • Default: false
    • Note: node-sass/libsass will compile a mixed library of scss and indented syntax (.sass) files with the Default setting (false) as long as .sass and .scss extensions are used in filenames. No cap. 🧚
  • indentType (>= v3.0.0) β€” used to determine whether to use space or tab character for indentation. The eternal debate. πŸ’€
    • Type: String
    • Default: space
  • indentWidth (>= v3.0.0) β€” used to determine the number of spaces or tabs to be used for indentation. How many? You decide. πŸ’…
    • Type: Number
    • Default: 2
    • Maximum: 10
  • linefeed (>= v3.0.0) β€” used to determine whether to use cr, crlf, lf or lfcr sequence for line break. It's giving line ending drama. 😭
    • Type: String
    • Default: lf
  • omitSourceMapUrl β€” true values disable the inclusion of source map information in the output file. No source map URL for you. πŸ™ˆ
    • Type: Boolean
    • Default: false
    • Special: When using this, you should also specify outFile to avoid unexpected behavior. iykyk. 🫢
  • outFile β€” specify the intended location of the output file. Strongly recommended when outputting source maps so that they can properly refer back to their intended files. It's giving "where should I put this?" πŸ“
    • Type: String | null
    • Default: null
    • Special: Required when sourceMap is a truthy value
Attention: enabling this option will not write the file on disk for you, it's for internal reference purpose only (to generate the map for example). Don't be fooled bestie. πŸ’…
  • Example on how to write it on the disk:
sass.render({
    ...
    outFile: yourPathTotheFile,
  }, function(error, result) { // node-style callback from v3.0.0 onwards
    if(!error){
      // No errors during the compilation, write this result on the disk
      fs.writeFile(yourPathTotheFile, result.css, function(err){
        if(!err){
          //file written on disk
        }
      });
    }
  });
});
  • outputStyle β€” determines the output format of the final CSS style. It's giving fashion week for CSS. πŸ‘‘
    • Type: String
    • Default: nested
    • Values: nested, expanded, compact, compressed
  • precision β€” used to determine how many digits after the decimal will be allowed. For instance, if you had a decimal number of 1.23456789 and a precision of 5, the result will be 1.23457 in the final CSS. Math is mathing. πŸ”’
    • Type: Integer
    • Default: 5
  • sourceComments β€” true Enables the line number and file where a selector is defined to be emitted into the compiled CSS as a comment. Useful for debugging, especially when using imports and mixins. It's giving "where did this come from?" πŸ•΅οΈ
    • Type: Boolean
    • Default: false
  • sourceMap β€” enables the outputting of a source map during render and renderSync. When sourceMap === true, the value of outFile is used as the target output location for the source map. When typeof sourceMap === "string", the value of sourceMap will be used as the writing location for the file. It's giving map energy. πŸ—ΊοΈ
    • Type: Boolean | String | undefined
    • Default: undefined
    • Special: Setting the sourceMap option requires also setting the outFile option. No cap. πŸ’…
  • sourceMapContents β€” true includes the contents in the source map information. It's giving extra detail. ✨
    • Type: Boolean
    • Default: false
  • sourceMapEmbed β€” true embeds the source map as a data URI. It's giving embedded vibes. πŸ”—
    • Type: Boolean
    • Default: false
  • sourceMapRoot β€” the value will be emitted as sourceRoot in the source map information. It's giving root access. 🌳
    • Type: String
    • Default: undefined

πŸ¦‹ render Callback (>= v3.0.0) πŸ¦‹

okay bestie, so node-sass is fully fluent in standard node-style async callbacks β€” the signature is literally function(err, result). When stuff goes wrong, the err argument gets populated with the error object. When stuff goes right, the result argument gets populated with an object describing how the render call went. Iconic behaviour, no notes. πŸ’…

😭 Error Object 😭

  • message (String) β€” the error message. The whole "what went wrong" tea.
  • line (Number) β€” the line number of error.
  • column (Number) β€” the column number of error.
  • status (Number) β€” the status code.
  • file (String) β€” the filename of error. And here's the little plot twist: if the file option was not set (because you went with data instead), this will reflect the value stdin.

✨ Result Object ✨

  • css (Buffer) β€” the compiled CSS. Write this to a file, or serve it out as needed. Do whatever, it's yours. 🫢
  • map (Buffer) β€” the source map.
  • stats (Object) β€” an object containing information about the compile. It contains the following keys:
    • entry (String) β€” the path to the scss file, or data if the source was not a file.
    • start (Number) β€” Date.now() before the compilation.
    • end (Number) β€” Date.now() after the compilation.
    • duration (Number) β€” end - start.
    • includedFiles (Array) β€” absolute paths to all related scss files in no particular order.

πŸŽ€ Examples πŸŽ€

var sass = require('node-sass');
sass.render({
  file: '/path/to/myFile.scss',
  data: 'body{background:blue; a{color:black;}}',
  importer: function(url, prev, done) {
    // url is the path in import as is, which LibSass encountered.
    // prev is the previously resolved path.
    // done is an optional callback, either consume it or return value synchronously.
    // this.options contains this options hash, this.callback contains the node-style callback
    someAsyncFunction(url, prev, function(result){
      done({
        file: result.path, // only one of them is required, see section Special Behaviours.
        contents: result.data
      });
    });
    // OR
    var result = someSyncFunction(url, prev);
    return {file: result.path, contents: result.data};
  },
  includePaths: [ 'lib/', 'mod/' ],
  outputStyle: 'compressed'
}, function(error, result) { // node-style callback from v3.0.0 onwards
  if (error) {
    console.log(error.status); // used to be "code" in v2x and below
    console.log(error.column);
    console.log(error.message);
    console.log(error.line);
  }
  else {
    console.log(result.css.toString());

    console.log(result.stats);

    console.log(result.map.toString());
    // or better
    console.log(JSON.stringify(result.map)); // note, JSON.stringify accepts Buffer too
  }
});
// OR
var result = sass.renderSync({
  file: '/path/to/file.scss',
  data: 'body{background:blue; a{color:black;}}',
  outputStyle: 'compressed',
  outFile: '/to/my/output.css',
  sourceMap: true, // or an absolute or relative (to outFile) path
  importer: function(url, prev, done) {
    // url is the path in import as is, which LibSass encountered.
    // prev is the previously resolved path.
    // done is an optional callback, either consume it or return value synchronously.
    // this.options contains this options hash
    someAsyncFunction(url, prev, function(result){
      done({
        file: result.path, // only one of them is required, see section Special Behaviours.
        contents: result.data
      });
    });
    // OR
    var result = someSyncFunction(url, prev);
    return {file: result.path, contents: result.data};
  }
}));

console.log(result.css);
console.log(result.map);
console.log(result.stats);

πŸ’€ Special behaviours πŸ’€

  • In the case that both file and data options are set, node-sass will give precedence to data and use file to calculate paths in sourcemaps. Yeah. data is the main character here, file is just doing the supporting role for sourcemaps. That's the vibe check. πŸ‘‘

🌸 Version information (>= v2.0.0) 🌸

Both node-sass and libsass version info is now exposed via the info method:

var sass = require('node-sass');

console.log(sass.info);

/*
  it will output something like:

  node-sass       2.0.1   (Wrapper)       [JavaScript]
  libsass         3.1.0   (Sass Compiler) [C/C++]
*/

Since node-sass >=v3.0.0 LibSass version is determined at run time. Not me knowing things ahead of time, nope. ✨


🌈 Integrations 🌈

A whole listing of community uses of node-sass in build tools and frameworks. The community ate, fr fr.

πŸ¦‹ Brackets extension πŸ¦‹

@jasonsanjose (https://github.com/jasonsanjose) has created a Brackets (http://brackets.io) extension based on node-sass: https://github.com/jasonsanjose/brackets-sass. When editing Sass files, the extension compiles changes on save. The extension also integrates with Live Preview to show Sass changes in the browser without saving or compiling. The way that it just... does that. πŸ˜­πŸ’–

πŸ“ Brunch plugin πŸ“

Brunch (http://brunch.io)'s official sass plugin uses node-sass by default, and automatically falls back to ruby if use of Compass is detected: https://github.com/brunch/sass-brunch

🧚 Connect/Express middleware 🧚

Recompile .scss files automatically for connect and express based http servers.

This functionality has been moved to node-sass-middleware (https://github.com/sass/node-sass-middleware) in node-sass v1.0.0. So if you're out here looking for it in the main repo, bestie, it moved. πŸ™ˆ

πŸ’œ DocPad Plugin πŸ’œ

@10xLaCroixDrinker (https://github.com/10xLaCroixDrinker) wrote a DocPad (http://docpad.org/) plugin that compiles .scss files using node-sass: https://github.com/10xLaCroixDrinker/docpad-plugin-nodesass

⭐ Duo.js extension ⭐

@stephenway (https://github.com/stephenway) has created an extension that transpiles Sass to CSS using node-sass with duo.js (http://duojs.org/) https://github.com/duojs/sass

πŸ”₯ Grunt extension πŸ”₯

@sindresorhus (https://github.com/sindresorhus/) has created a set of grunt tasks based on node-sass: https://github.com/sindresorhus/grunt-sass

πŸŽ€ Gulp extension πŸŽ€

@dlmanning (https://github.com/dlmanning/) has created a gulp sass plugin based on node-sass: https://github.com/dlmanning/gulp-sass

🌸 Harp 🌸

@sintaxi (https://github.com/sintaxi's) Harp web server implicitly compiles .scss files using node-sass: https://github.com/sintaxi/harp

πŸ’… Metalsmith plugin πŸ’…

@stevenschobert (https://github.com/stevenschobert/) has created a metalsmith plugin based on node-sass: https://github.com/stevenschobert/metalsmith-sass

πŸ‘‘ Meteor plugin πŸ‘‘

@fourseven (https://github.com/fourseven) has created a meteor plugin based on node-sass: https://github.com/fourseven/meteor-scss

πŸ¦‹ Mimosa module πŸ¦‹

@dbashford (https://github.com/dbashford) has created a Mimosa module for sass which includes node-sass: https://github.com/dbashford/mimosa-sass


✨ Example App ✨

There is also an example connect app here: https://github.com/andrew/node-sass-example


πŸ”₯ Rebuilding binaries πŸ”₯

Node-sass includes pre-compiled binaries for popular platforms, to add a binary for your platform follow these steps:

Check out the project:

git clone --recursive https://github.com/sass/node-sass.git
cd node-sass
npm install
node scripts/build -f  # use -d switch for debug release
# if succeeded, it will generate and move
# the binary in vendor directory.

πŸ‘‘ Command Line Interface πŸ‘‘

The interface for command-line usage is fairly simplistic at this stage, as seen in the following usage section. It's giving "small but mighty", honestly.

Output will be sent to stdout if the --output flag is omitted.

🌈 Usage 🌈

node-sass [options] <input> [output]
Or:
cat <input> | node-sass > output

Example:

node-sass src/style.scss dest/style.css

✨ Options ✨

  • -w, --watch β€” Watch a directory or file
  • -r, --recursive β€” Recursively watch directories or files
  • -o, --output β€” Output directory
  • -x, --omit-source-map-url β€” Omit source map URL comment from output
  • -i, --indented-syntax β€” Treat data from stdin as sass code (versus scss)
  • -q, --quiet β€” Suppress log output except on error
  • -v, --version β€” Prints version info
  • --output-style β€” CSS output style (nested | expanded | compact | compressed)
  • --indent-type β€” Indent type for output CSS (space | tab)
  • --indent-width β€” Indent width; number of spaces or tabs (maximum value: 10)
  • --linefeed β€” Linefeed style (cr | crlf | lf | lfcr)
  • --source-comments β€” Include debug info in output
  • --source-map β€” Emit source map
  • --source-map-contents β€” Embed include contents in map
  • --source-map-embed β€” Embed sourceMappingUrl as data URI
  • --source-map-root β€” Base path, will be emitted in source-map as is
  • --include-path β€” Path to look for imported files
  • --follow β€” Follow symlinked directories
  • --precision β€” The amount of precision allowed in decimal numbers
  • --error-bell β€” Output a bell character on errors
  • --importer β€” Path to .js file containing custom importer
  • --functions β€” Path to .js file containing custom functions
  • --help β€” Print usage info

The input can be either a single .scss or .sass, or a directory. If the input is a directory the --output flag must also be supplied. Like, mandatory mandatory. 🫢

Also, note --importer takes the (absolute or relative to pwd) path to a js file, which needs to have a default module.exports set to the importer function. See our test fixtures https://github.com/sass/node-sass/tree/974f93e76ddd08ea850e3e663cfe64bb6a059dd3/test/fixtures/extras for example.

The --source-map option accepts a boolean value, in which case it replaces destination extension with .css.map. It also accepts path to .map file and even path to the desired directory. When compiling a directory --source-map can either be a boolean value or a directory.

🌈 Binary configuration parameters

okay so listen πŸ’– node-sass lets you switch up settings for the sass binary β€” stuff like what it's called, where it lives, or where it gets downloaded from. here's every parameter it supports, no cap:

  • SASS_BINARY_NAME / sass_binary_name / --sass-binary-name β€” value: path
  • SASS_BINARY_SITE / sass_binary_site / --sass-binary-site β€” value: URL
  • SASS_BINARY_PATH / sass_binary_path / --sass-binary-path β€” value: path
  • SASS_BINARY_DIR / sass_binary_dir / --sass-binary-dir β€” value: path

so like, first column is the variable name, second is the .npmrc parameter, third is the process argument, fourth is the value type πŸŽ€

and you can use these three different ways bestie, pick your fighter:


πŸ¦‹ Post-install Build

when you install, it literally only runs two Mocha tests to check if your machine can use the pre-built LibSass (https://github.com/sass/libsass) β€” that's the whole point, it saves you some time during install 🫢

but if any of those tests fail, it's building from source. no shortcuts, bestie 😭

πŸ‘‘ Maintainers

this module is brought to you and maintained by these absolute icons, show some respect:


πŸ’œ Contributors

we <3 our contributors!! a special thanks to literally everyone who clocked in some dev time on this project, we really appreciate your hard work fr fr πŸ₯Ή

you can find the full list of those people right here: https://github.com/sass/node-sass/graphs/contributors

πŸŽ€ Note on Patches/Pull Requests

check out our Contributing guide at /.github/CONTRIBUTING.md β€” go read it before you slide into the PRs bestie ✨


Copyright (c) 2015 Andrew Nesbitt. See LICENSE (https://github.com/sass/node-sass/blob/master/LICENSE) for details.


and that's the whole page, you made it to the end πŸπŸ’– this was the January 2020 edition of NODE-SASS(), so if you're reading this from the future, hi, hope the binaries still build 🫢 slay, go write some sass, periodt πŸ’…βœ¨