CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-sass-loader

Sass loader for webpack that compiles Sass/SCSS files to CSS during the build process

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

sass-loader

sass-loader is a webpack loader that compiles Sass/SCSS files to CSS during the webpack build process. It acts as a bridge between Sass preprocessors (Dart Sass, Node Sass, or Sass Embedded) and webpack's module system, enabling seamless integration of Sass stylesheets in JavaScript applications.

Package Information

  • Package Name: sass-loader
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install sass-loader sass webpack --save-dev

Core Imports

// CommonJS (primary usage)
const sassLoader = require("sass-loader");

// ES Modules (source)
import sassLoader from "sass-loader";

Basic Usage

Configure sass-loader in your webpack configuration:

module.exports = {
  module: {
    rules: [
      {
        test: /\.s[ac]ss$/i,
        use: [
          // Creates `style` nodes from JS strings
          "style-loader",
          // Translates CSS into CommonJS
          "css-loader",
          // Compiles Sass to CSS
          "sass-loader",
        ],
      },
    ],
  },
};

With custom options:

module.exports = {
  module: {
    rules: [
      {
        test: /\.s[ac]ss$/i,
        use: [
          "style-loader",
          "css-loader",
          {
            loader: "sass-loader",
            options: {
              implementation: require("sass"),
              sassOptions: {
                indentWidth: 4,
                includePaths: [path.resolve(__dirname, "src/styles")],
              },
            },
          },
        ],
      },
    ],
  },
};

Architecture

sass-loader implements the webpack loader interface and orchestrates Sass compilation through several key components:

  • Main Loader Function: Processes Sass/SCSS content and returns compiled CSS
  • Implementation Detection: Automatically detects available Sass implementations (sass, node-sass, sass-embedded)
  • API Type Handling: Supports both legacy (node-sass) and modern (dart-sass/sass-embedded) APIs
  • Webpack Integration: Handles dependency tracking and source map generation
  • Import Resolution: Custom importers for webpack-style module resolution

Capabilities

Sass Compilation

Primary loader function that compiles Sass/SCSS content to CSS.

function loader(content: string): Promise<void>;

The loader is an async function that:

  • Receives Sass/SCSS source content as input
  • Processes options and determines Sass implementation
  • Compiles the content using the appropriate Sass API
  • Returns compiled CSS with optional source maps
  • Automatically tracks file dependencies for webpack's watch mode

Configuration Options

sass-loader accepts the following options object:

interface SassLoaderOptions {
  implementation?: string | object;
  api?: "legacy" | "modern" | "modern-compiler";
  sassOptions?: object | function;
  additionalData?: string | function;
  sourceMap?: boolean;
  webpackImporter?: boolean;
  warnRuleAsWarning?: boolean;
}

implementation: Specifies which Sass implementation to use. Can be a string (package name) or the implementation object itself. Defaults to auto-detection in order: sass-embedded, sass, node-sass.

api: Controls which Sass API to use. "legacy" for node-sass compatibility, "modern" for dart-sass/sass-embedded features, "modern-compiler" for advanced compilation features.

sassOptions: Options passed directly to the Sass implementation. Can be an object or a function that returns options dynamically based on loader context.

additionalData: String or function that prepends/appends Sass code before the actual entry file. Useful for injecting global variables or mixins.

sourceMap: Boolean to enable/disable source map generation. Defaults to webpack's devtool setting.

webpackImporter: Boolean to enable/disable webpack's module resolution for Sass @import statements. Defaults to true.

warnRuleAsWarning: Boolean to treat Sass @warn rules as webpack warnings instead of console output.

Sass Implementation Support

sass-loader supports multiple Sass implementations with automatic detection:

function getSassImplementation(
  loaderContext: object,
  implementation?: string | object
): object;

Supported implementations:

  • sass (Dart Sass): Modern, actively maintained implementation
  • sass-embedded: Embedded Dart Sass for improved performance
  • node-sass: Legacy implementation (deprecated but still supported)

The loader automatically detects available implementations in this priority order: sass-embedded → sass → node-sass.

Sass Options Processing

Derives and normalizes Sass options from loader configuration:

function getSassOptions(
  loaderContext: object,
  loaderOptions: object,
  content: string,
  implementation: object,
  useSourceMap: boolean,
  apiType: string
): Promise<object>;

Processes loader options to create the final Sass configuration object:

  • Merges user-provided sassOptions with defaults
  • Handles additionalData injection (strings or functions)
  • Sets up logging and warning systems
  • Configures source map generation
  • Prepares options for the target Sass API (legacy/modern)

Webpack Resolver Integration

Creates webpack-compatible resolver functions:

function getWebpackResolver(
  resolverFactory: Function,
  implementation: object,
  includePaths?: string[]
): function;

Provides webpack module resolution for Sass import statements:

  • Integrates with webpack's enhanced-resolve system
  • Supports node_modules resolution
  • Handles package.json main field resolution
  • Works with webpack's resolve configuration

Compilation Function Factory

Returns appropriate compilation function based on Sass implementation and API type:

function getCompileFn(
  loaderContext: object,
  implementation: object,
  apiType: string
): function;

Provides unified compilation interface:

  • Abstracts differences between Sass implementations
  • Handles legacy vs modern API compatibility
  • Manages async/sync compilation modes
  • Provides consistent error handling across implementations

Import Resolution

sass-loader provides webpack-compatible import resolution for Sass files:

function getWebpackImporter(
  loaderContext: object, 
  implementation: object,
  includePaths: string[]
): function;

function getModernWebpackImporter(
  loaderContext: object,
  implementation: object, 
  loadPaths: string[]
): object;

Features:

  • Resolves @import statements using webpack's module resolution
  • Supports importing from node_modules with ~ prefix
  • Handles relative and absolute path imports
  • Compatible with both legacy and modern Sass APIs

Source Map Handling

Source map generation and normalization for webpack integration:

function normalizeSourceMap(map: object, rootContext: string): object;
  • Generates source maps when enabled
  • Normalizes source paths for webpack compatibility
  • Supports both legacy and modern source map formats
  • Integrates with webpack's devtool configuration

Error Handling

Standardized error processing for Sass compilation failures:

function errorFactory(error: Error): Error;
  • Formats Sass compilation errors consistently
  • Preserves file location information from Sass errors
  • Integrates with webpack's error reporting system
  • Handles differences between Sass implementation error formats

Usage Examples

Basic Sass File Processing

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: ["style-loader", "css-loader", "sass-loader"],
      },
    ],
  },
};

Custom Sass Implementation

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: [
          "style-loader",
          "css-loader",
          {
            loader: "sass-loader",
            options: {
              implementation: require("sass"),
              api: "modern",
            },
          },
        ],
      },
    ],
  },
};

Global Variables and Mixins

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: [
          "style-loader",
          "css-loader",
          {
            loader: "sass-loader",
            options: {
              additionalData: `
                $primary-color: #007bff;
                @import "src/styles/variables";
              `,
            },
          },
        ],
      },
    ],
  },
};

Dynamic Sass Options

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: [
          "style-loader",
          "css-loader",
          {
            loader: "sass-loader",
            options: {
              sassOptions: (loaderContext) => {
                return {
                  includePaths: [
                    path.resolve(__dirname, "src/styles"),
                    path.resolve(__dirname, "node_modules"),
                  ],
                  outputStyle: loaderContext.mode === "production" ? "compressed" : "expanded",
                };
              },
            },
          },
        ],
      },
    ],
  },
};

Types

interface LoaderContext {
  getOptions(schema?: object): object;
  async(): function;
  addDependency(file: string): void;
  sourceMap: boolean;
  mode: string;
  rootContext: string;
}

interface SassOptions {
  includePaths?: string[];
  indentWidth?: number;
  outputStyle?: "expanded" | "compressed";
  sourceMap?: boolean;
  importer?: function[];
  importers?: object[];
}

interface CompilationResult {
  css: Buffer | string;
  map?: string;
  sourceMap?: object;
  stats?: {
    includedFiles: string[];
  };
  loadedUrls?: URL[];
}
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/sass-loader@16.0.x
Publish Source
CLI
Badge
tessl/npm-sass-loader badge