CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-node-sass

Node.js wrapper around libsass for compiling Sass and SCSS files to CSS

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

compilation.mddocs/

Core Compilation

Primary Sass/SCSS compilation functionality for converting stylesheets to CSS with comprehensive configuration options and error handling.

Capabilities

Asynchronous Render

Asynchronously compiles Sass/SCSS to CSS with callback-based error handling.

/**
 * Asynchronously render Sass/SCSS to CSS
 * @param options - Compilation options object
 * @param callback - Callback function (error: SassError | null, result?: RenderResult) => void
 */
function render(options, callback);

interface RenderOptions {
  // Input options (one required)
  file?: string;                    // Path to input .sass or .scss file
  data?: string;                    // Sass/SCSS string to compile

  // Output options
  outFile?: string;                 // Path for output CSS file
  outputStyle?: "nested" | "expanded" | "compact" | "compressed";
  sourceMap?: boolean | string;     // Generate source map (true/false or output path)
  sourceMapContents?: boolean;      // Include source contents in source map
  sourceMapEmbed?: boolean;         // Embed source map as data URI
  sourceMapRoot?: string;           // Base path for source map URLs
  
  // Processing options
  includePaths?: string[];          // Additional paths for @import resolution
  precision?: number;               // Decimal precision for numbers (default: 5)
  sourceComments?: boolean;         // Include line comments in output (default: false)
  
  // Formatting options
  indentType?: "space" | "tab";     // Indentation type (default: "space")
  indentWidth?: number;             // Indentation width (default: 2, max: 10)
  linefeed?: "cr" | "crlf" | "lf" | "lfcr"; // Line ending style (default: "lf")
  
  // Advanced options
  functions?: { [signature: string]: Function }; // Custom Sass functions
  importer?: Function | Function[]; // Custom import resolution
}

interface RenderResult {
  css: Buffer;                      // Compiled CSS output
  map?: Buffer;                     // Source map data (if enabled)
  stats: {
    entry: string;                  // Entry file path or "data"
    start: number;                  // Start timestamp
    end: number;                    // End timestamp  
    duration: number;               // Compilation duration in milliseconds
  };
}

Usage Examples:

const sass = require("node-sass");

// Compile from file with options
sass.render({
  file: "styles/main.scss",
  outFile: "dist/main.css",
  outputStyle: "compressed",
  sourceMap: true,
  includePaths: ["node_modules", "styles/partials"]
}, (error, result) => {
  if (error) {
    console.error("Sass compilation failed:", error.message);
    console.error("Line:", error.line, "Column:", error.column);
  } else {
    console.log("CSS:", result.css.toString());
    console.log("Source map:", result.map.toString());
    console.log("Duration:", result.stats.duration, "ms");
  }
});

// Compile from string data
sass.render({
  data: `
    $primary: #3498db;
    $secondary: #2ecc71;
    
    .header {
      background: $primary;
      color: white;
      
      .nav {
        background: $secondary;
      }
    }
  `,
  outputStyle: "expanded"
}, (error, result) => {
  if (!error) {
    console.log(result.css.toString());
  }
});

Synchronous Render

Synchronously compiles Sass/SCSS to CSS with exception-based error handling.

/**
 * Synchronously render Sass/SCSS to CSS
 * @param options - Compilation options (same as render)
 * @returns RenderResult object
 * @throws Error on compilation failure
 */
function renderSync(options);

Usage Examples:

const sass = require("node-sass");

// Synchronous compilation
try {
  const result = sass.renderSync({
    file: "input.scss",
    outputStyle: "compressed",
    sourceMap: "output.css.map"
  });
  
  console.log("Compiled CSS:", result.css.toString());
  if (result.map) {
    console.log("Source map:", result.map.toString());
  }
} catch (error) {
  console.error("Compilation error:", error.message);
  console.error("File:", error.file);
  console.error("Line:", error.line, "Column:", error.column);
}

// Quick string compilation
try {
  const result = sass.renderSync({
    data: ".test { color: darken(#3498db, 20%); }",
    outputStyle: "expanded"
  });
  console.log(result.css.toString());
} catch (error) {
  console.error(error.message);
}

Custom Functions

Define custom Sass functions that can be called from within stylesheets.

interface CustomFunction {
  (done: (result: SassValue) => void): void;
  // Function receives Sass arguments and calls done() with result
}

// Function signature formats:
// "functionName(...)" - Variable arguments passed as SassList
// "functionName($arg1, $arg2)" - Named arguments
// "functionName($arg: defaultValue)" - Arguments with defaults

Usage Example:

sass.render({
  data: `
    .test {
      width: double(50px);
      color: random-color();
    }
  `,
  functions: {
    // Simple function with variable arguments
    "double(...)": function(args, done) {
      const value = args.getValue(0);
      const doubled = new sass.types.Number(
        value.getValue() * 2,
        value.getUnit()
      );
      done(doubled);
    },
    
    // Function with no arguments
    "random-color()": function(done) {
      const r = Math.floor(Math.random() * 256);
      const g = Math.floor(Math.random() * 256);
      const b = Math.floor(Math.random() * 256);
      const color = new sass.types.Color(r, g, b);
      done(color);
    }
  }
}, (error, result) => {
  if (!error) {
    console.log(result.css.toString());
  }
});

Custom Importers

Control how @import statements are resolved and processed.

interface CustomImporter {
  (url: string, prev: string, done: (result: ImporterResult) => void): void;
  // Can also return ImporterResult synchronously (for renderSync)
}

interface ImporterResult {
  file?: string;                    // Absolute path to import
  contents?: string;                // File contents to use instead of reading from disk
}

Usage Example:

sass.render({
  file: "main.scss",
  importer: function(url, prev, done) {
    // Custom logic for resolving imports
    if (url.startsWith("npm:")) {
      const packageName = url.slice(4);
      const packagePath = require.resolve(packageName);
      done({ file: packagePath });
    } else if (url.startsWith("virtual:")) {
      // Return virtual file contents
      done({
        contents: ".virtual { content: 'This is virtual'; }"
      });
    } else {
      // Let Sass handle normally
      done(null);
    }
  }
}, (error, result) => {
  if (!error) {
    console.log(result.css.toString());
  }
});

Error Handling

Comprehensive error information for debugging compilation issues.

interface SassError extends Error {
  message: string;                  // Error description
  line: number;                     // Line number where error occurred
  column: number;                   // Column number where error occurred
  file: string;                     // File path where error occurred
  status: number;                   // Error status code
}

Common Error Types:

  • Syntax errors: Invalid Sass/SCSS syntax
  • Import errors: File not found or circular imports
  • Type errors: Invalid operations or function calls
  • Custom function errors: Errors in custom function implementations
sass.render({
  data: ".test { color: invalid-function(); }"
}, (error, result) => {
  if (error) {
    console.log("Error:", error.message);
    console.log("Location: Line", error.line, "Column", error.column);
    console.log("Status:", error.status);
  }
});

docs

cli.md

compilation.md

environment.md

index.md

types.md

tile.json