0
# sass-loader
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: sass-loader
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install sass-loader sass webpack --save-dev`
10
11
## Core Imports
12
13
```javascript
14
// CommonJS (primary usage)
15
const sassLoader = require("sass-loader");
16
17
// ES Modules (source)
18
import sassLoader from "sass-loader";
19
```
20
21
## Basic Usage
22
23
Configure sass-loader in your webpack configuration:
24
25
```javascript
26
module.exports = {
27
module: {
28
rules: [
29
{
30
test: /\.s[ac]ss$/i,
31
use: [
32
// Creates `style` nodes from JS strings
33
"style-loader",
34
// Translates CSS into CommonJS
35
"css-loader",
36
// Compiles Sass to CSS
37
"sass-loader",
38
],
39
},
40
],
41
},
42
};
43
```
44
45
With custom options:
46
47
```javascript
48
module.exports = {
49
module: {
50
rules: [
51
{
52
test: /\.s[ac]ss$/i,
53
use: [
54
"style-loader",
55
"css-loader",
56
{
57
loader: "sass-loader",
58
options: {
59
implementation: require("sass"),
60
sassOptions: {
61
indentWidth: 4,
62
includePaths: [path.resolve(__dirname, "src/styles")],
63
},
64
},
65
},
66
],
67
},
68
],
69
},
70
};
71
```
72
73
## Architecture
74
75
sass-loader implements the webpack loader interface and orchestrates Sass compilation through several key components:
76
77
- **Main Loader Function**: Processes Sass/SCSS content and returns compiled CSS
78
- **Implementation Detection**: Automatically detects available Sass implementations (sass, node-sass, sass-embedded)
79
- **API Type Handling**: Supports both legacy (node-sass) and modern (dart-sass/sass-embedded) APIs
80
- **Webpack Integration**: Handles dependency tracking and source map generation
81
- **Import Resolution**: Custom importers for webpack-style module resolution
82
83
## Capabilities
84
85
### Sass Compilation
86
87
Primary loader function that compiles Sass/SCSS content to CSS.
88
89
```javascript { .api }
90
function loader(content: string): Promise<void>;
91
```
92
93
The loader is an async function that:
94
- Receives Sass/SCSS source content as input
95
- Processes options and determines Sass implementation
96
- Compiles the content using the appropriate Sass API
97
- Returns compiled CSS with optional source maps
98
- Automatically tracks file dependencies for webpack's watch mode
99
100
### Configuration Options
101
102
sass-loader accepts the following options object:
103
104
```javascript { .api }
105
interface SassLoaderOptions {
106
implementation?: string | object;
107
api?: "legacy" | "modern" | "modern-compiler";
108
sassOptions?: object | function;
109
additionalData?: string | function;
110
sourceMap?: boolean;
111
webpackImporter?: boolean;
112
warnRuleAsWarning?: boolean;
113
}
114
```
115
116
**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.
117
118
**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.
119
120
**sassOptions**: Options passed directly to the Sass implementation. Can be an object or a function that returns options dynamically based on loader context.
121
122
**additionalData**: String or function that prepends/appends Sass code before the actual entry file. Useful for injecting global variables or mixins.
123
124
**sourceMap**: Boolean to enable/disable source map generation. Defaults to webpack's devtool setting.
125
126
**webpackImporter**: Boolean to enable/disable webpack's module resolution for Sass @import statements. Defaults to true.
127
128
**warnRuleAsWarning**: Boolean to treat Sass @warn rules as webpack warnings instead of console output.
129
130
### Sass Implementation Support
131
132
sass-loader supports multiple Sass implementations with automatic detection:
133
134
```javascript { .api }
135
function getSassImplementation(
136
loaderContext: object,
137
implementation?: string | object
138
): object;
139
```
140
141
Supported implementations:
142
- **sass** (Dart Sass): Modern, actively maintained implementation
143
- **sass-embedded**: Embedded Dart Sass for improved performance
144
- **node-sass**: Legacy implementation (deprecated but still supported)
145
146
The loader automatically detects available implementations in this priority order: sass-embedded → sass → node-sass.
147
148
### Sass Options Processing
149
150
Derives and normalizes Sass options from loader configuration:
151
152
```javascript { .api }
153
function getSassOptions(
154
loaderContext: object,
155
loaderOptions: object,
156
content: string,
157
implementation: object,
158
useSourceMap: boolean,
159
apiType: string
160
): Promise<object>;
161
```
162
163
Processes loader options to create the final Sass configuration object:
164
- Merges user-provided sassOptions with defaults
165
- Handles additionalData injection (strings or functions)
166
- Sets up logging and warning systems
167
- Configures source map generation
168
- Prepares options for the target Sass API (legacy/modern)
169
170
### Webpack Resolver Integration
171
172
Creates webpack-compatible resolver functions:
173
174
```javascript { .api }
175
function getWebpackResolver(
176
resolverFactory: Function,
177
implementation: object,
178
includePaths?: string[]
179
): function;
180
```
181
182
Provides webpack module resolution for Sass import statements:
183
- Integrates with webpack's enhanced-resolve system
184
- Supports node_modules resolution
185
- Handles package.json main field resolution
186
- Works with webpack's resolve configuration
187
188
### Compilation Function Factory
189
190
Returns appropriate compilation function based on Sass implementation and API type:
191
192
```javascript { .api }
193
function getCompileFn(
194
loaderContext: object,
195
implementation: object,
196
apiType: string
197
): function;
198
```
199
200
Provides unified compilation interface:
201
- Abstracts differences between Sass implementations
202
- Handles legacy vs modern API compatibility
203
- Manages async/sync compilation modes
204
- Provides consistent error handling across implementations
205
206
### Import Resolution
207
208
sass-loader provides webpack-compatible import resolution for Sass files:
209
210
```javascript { .api }
211
function getWebpackImporter(
212
loaderContext: object,
213
implementation: object,
214
includePaths: string[]
215
): function;
216
217
function getModernWebpackImporter(
218
loaderContext: object,
219
implementation: object,
220
loadPaths: string[]
221
): object;
222
```
223
224
Features:
225
- Resolves `@import` statements using webpack's module resolution
226
- Supports importing from node_modules with `~` prefix
227
- Handles relative and absolute path imports
228
- Compatible with both legacy and modern Sass APIs
229
230
### Source Map Handling
231
232
Source map generation and normalization for webpack integration:
233
234
```javascript { .api }
235
function normalizeSourceMap(map: object, rootContext: string): object;
236
```
237
238
- Generates source maps when enabled
239
- Normalizes source paths for webpack compatibility
240
- Supports both legacy and modern source map formats
241
- Integrates with webpack's devtool configuration
242
243
### Error Handling
244
245
Standardized error processing for Sass compilation failures:
246
247
```javascript { .api }
248
function errorFactory(error: Error): Error;
249
```
250
251
- Formats Sass compilation errors consistently
252
- Preserves file location information from Sass errors
253
- Integrates with webpack's error reporting system
254
- Handles differences between Sass implementation error formats
255
256
## Usage Examples
257
258
### Basic Sass File Processing
259
260
```javascript
261
// webpack.config.js
262
module.exports = {
263
module: {
264
rules: [
265
{
266
test: /\.scss$/,
267
use: ["style-loader", "css-loader", "sass-loader"],
268
},
269
],
270
},
271
};
272
```
273
274
### Custom Sass Implementation
275
276
```javascript
277
// webpack.config.js
278
module.exports = {
279
module: {
280
rules: [
281
{
282
test: /\.scss$/,
283
use: [
284
"style-loader",
285
"css-loader",
286
{
287
loader: "sass-loader",
288
options: {
289
implementation: require("sass"),
290
api: "modern",
291
},
292
},
293
],
294
},
295
],
296
},
297
};
298
```
299
300
### Global Variables and Mixins
301
302
```javascript
303
// webpack.config.js
304
module.exports = {
305
module: {
306
rules: [
307
{
308
test: /\.scss$/,
309
use: [
310
"style-loader",
311
"css-loader",
312
{
313
loader: "sass-loader",
314
options: {
315
additionalData: `
316
$primary-color: #007bff;
317
@import "src/styles/variables";
318
`,
319
},
320
},
321
],
322
},
323
],
324
},
325
};
326
```
327
328
### Dynamic Sass Options
329
330
```javascript
331
// webpack.config.js
332
module.exports = {
333
module: {
334
rules: [
335
{
336
test: /\.scss$/,
337
use: [
338
"style-loader",
339
"css-loader",
340
{
341
loader: "sass-loader",
342
options: {
343
sassOptions: (loaderContext) => {
344
return {
345
includePaths: [
346
path.resolve(__dirname, "src/styles"),
347
path.resolve(__dirname, "node_modules"),
348
],
349
outputStyle: loaderContext.mode === "production" ? "compressed" : "expanded",
350
};
351
},
352
},
353
},
354
],
355
},
356
],
357
},
358
};
359
```
360
361
## Types
362
363
```javascript { .api }
364
interface LoaderContext {
365
getOptions(schema?: object): object;
366
async(): function;
367
addDependency(file: string): void;
368
sourceMap: boolean;
369
mode: string;
370
rootContext: string;
371
}
372
373
interface SassOptions {
374
includePaths?: string[];
375
indentWidth?: number;
376
outputStyle?: "expanded" | "compressed";
377
sourceMap?: boolean;
378
importer?: function[];
379
importers?: object[];
380
}
381
382
interface CompilationResult {
383
css: Buffer | string;
384
map?: string;
385
sourceMap?: object;
386
stats?: {
387
includedFiles: string[];
388
};
389
loadedUrls?: URL[];
390
}
391
```