0
# Core Compilation
1
2
Primary Sass/SCSS compilation functionality for converting stylesheets to CSS with comprehensive configuration options and error handling.
3
4
## Capabilities
5
6
### Asynchronous Render
7
8
Asynchronously compiles Sass/SCSS to CSS with callback-based error handling.
9
10
```javascript { .api }
11
/**
12
* Asynchronously render Sass/SCSS to CSS
13
* @param options - Compilation options object
14
* @param callback - Callback function (error: SassError | null, result?: RenderResult) => void
15
*/
16
function render(options, callback);
17
18
interface RenderOptions {
19
// Input options (one required)
20
file?: string; // Path to input .sass or .scss file
21
data?: string; // Sass/SCSS string to compile
22
23
// Output options
24
outFile?: string; // Path for output CSS file
25
outputStyle?: "nested" | "expanded" | "compact" | "compressed";
26
sourceMap?: boolean | string; // Generate source map (true/false or output path)
27
sourceMapContents?: boolean; // Include source contents in source map
28
sourceMapEmbed?: boolean; // Embed source map as data URI
29
sourceMapRoot?: string; // Base path for source map URLs
30
31
// Processing options
32
includePaths?: string[]; // Additional paths for @import resolution
33
precision?: number; // Decimal precision for numbers (default: 5)
34
sourceComments?: boolean; // Include line comments in output (default: false)
35
36
// Formatting options
37
indentType?: "space" | "tab"; // Indentation type (default: "space")
38
indentWidth?: number; // Indentation width (default: 2, max: 10)
39
linefeed?: "cr" | "crlf" | "lf" | "lfcr"; // Line ending style (default: "lf")
40
41
// Advanced options
42
functions?: { [signature: string]: Function }; // Custom Sass functions
43
importer?: Function | Function[]; // Custom import resolution
44
}
45
46
interface RenderResult {
47
css: Buffer; // Compiled CSS output
48
map?: Buffer; // Source map data (if enabled)
49
stats: {
50
entry: string; // Entry file path or "data"
51
start: number; // Start timestamp
52
end: number; // End timestamp
53
duration: number; // Compilation duration in milliseconds
54
};
55
}
56
```
57
58
**Usage Examples:**
59
60
```javascript
61
const sass = require("node-sass");
62
63
// Compile from file with options
64
sass.render({
65
file: "styles/main.scss",
66
outFile: "dist/main.css",
67
outputStyle: "compressed",
68
sourceMap: true,
69
includePaths: ["node_modules", "styles/partials"]
70
}, (error, result) => {
71
if (error) {
72
console.error("Sass compilation failed:", error.message);
73
console.error("Line:", error.line, "Column:", error.column);
74
} else {
75
console.log("CSS:", result.css.toString());
76
console.log("Source map:", result.map.toString());
77
console.log("Duration:", result.stats.duration, "ms");
78
}
79
});
80
81
// Compile from string data
82
sass.render({
83
data: `
84
$primary: #3498db;
85
$secondary: #2ecc71;
86
87
.header {
88
background: $primary;
89
color: white;
90
91
.nav {
92
background: $secondary;
93
}
94
}
95
`,
96
outputStyle: "expanded"
97
}, (error, result) => {
98
if (!error) {
99
console.log(result.css.toString());
100
}
101
});
102
```
103
104
### Synchronous Render
105
106
Synchronously compiles Sass/SCSS to CSS with exception-based error handling.
107
108
```javascript { .api }
109
/**
110
* Synchronously render Sass/SCSS to CSS
111
* @param options - Compilation options (same as render)
112
* @returns RenderResult object
113
* @throws Error on compilation failure
114
*/
115
function renderSync(options);
116
```
117
118
**Usage Examples:**
119
120
```javascript
121
const sass = require("node-sass");
122
123
// Synchronous compilation
124
try {
125
const result = sass.renderSync({
126
file: "input.scss",
127
outputStyle: "compressed",
128
sourceMap: "output.css.map"
129
});
130
131
console.log("Compiled CSS:", result.css.toString());
132
if (result.map) {
133
console.log("Source map:", result.map.toString());
134
}
135
} catch (error) {
136
console.error("Compilation error:", error.message);
137
console.error("File:", error.file);
138
console.error("Line:", error.line, "Column:", error.column);
139
}
140
141
// Quick string compilation
142
try {
143
const result = sass.renderSync({
144
data: ".test { color: darken(#3498db, 20%); }",
145
outputStyle: "expanded"
146
});
147
console.log(result.css.toString());
148
} catch (error) {
149
console.error(error.message);
150
}
151
```
152
153
### Custom Functions
154
155
Define custom Sass functions that can be called from within stylesheets.
156
157
```javascript { .api }
158
interface CustomFunction {
159
(done: (result: SassValue) => void): void;
160
// Function receives Sass arguments and calls done() with result
161
}
162
163
// Function signature formats:
164
// "functionName(...)" - Variable arguments passed as SassList
165
// "functionName($arg1, $arg2)" - Named arguments
166
// "functionName($arg: defaultValue)" - Arguments with defaults
167
```
168
169
**Usage Example:**
170
171
```javascript
172
sass.render({
173
data: `
174
.test {
175
width: double(50px);
176
color: random-color();
177
}
178
`,
179
functions: {
180
// Simple function with variable arguments
181
"double(...)": function(args, done) {
182
const value = args.getValue(0);
183
const doubled = new sass.types.Number(
184
value.getValue() * 2,
185
value.getUnit()
186
);
187
done(doubled);
188
},
189
190
// Function with no arguments
191
"random-color()": function(done) {
192
const r = Math.floor(Math.random() * 256);
193
const g = Math.floor(Math.random() * 256);
194
const b = Math.floor(Math.random() * 256);
195
const color = new sass.types.Color(r, g, b);
196
done(color);
197
}
198
}
199
}, (error, result) => {
200
if (!error) {
201
console.log(result.css.toString());
202
}
203
});
204
```
205
206
### Custom Importers
207
208
Control how @import statements are resolved and processed.
209
210
```javascript { .api }
211
interface CustomImporter {
212
(url: string, prev: string, done: (result: ImporterResult) => void): void;
213
// Can also return ImporterResult synchronously (for renderSync)
214
}
215
216
interface ImporterResult {
217
file?: string; // Absolute path to import
218
contents?: string; // File contents to use instead of reading from disk
219
}
220
```
221
222
**Usage Example:**
223
224
```javascript
225
sass.render({
226
file: "main.scss",
227
importer: function(url, prev, done) {
228
// Custom logic for resolving imports
229
if (url.startsWith("npm:")) {
230
const packageName = url.slice(4);
231
const packagePath = require.resolve(packageName);
232
done({ file: packagePath });
233
} else if (url.startsWith("virtual:")) {
234
// Return virtual file contents
235
done({
236
contents: ".virtual { content: 'This is virtual'; }"
237
});
238
} else {
239
// Let Sass handle normally
240
done(null);
241
}
242
}
243
}, (error, result) => {
244
if (!error) {
245
console.log(result.css.toString());
246
}
247
});
248
```
249
250
### Error Handling
251
252
Comprehensive error information for debugging compilation issues.
253
254
```javascript { .api }
255
interface SassError extends Error {
256
message: string; // Error description
257
line: number; // Line number where error occurred
258
column: number; // Column number where error occurred
259
file: string; // File path where error occurred
260
status: number; // Error status code
261
}
262
```
263
264
**Common Error Types:**
265
266
- **Syntax errors**: Invalid Sass/SCSS syntax
267
- **Import errors**: File not found or circular imports
268
- **Type errors**: Invalid operations or function calls
269
- **Custom function errors**: Errors in custom function implementations
270
271
```javascript
272
sass.render({
273
data: ".test { color: invalid-function(); }"
274
}, (error, result) => {
275
if (error) {
276
console.log("Error:", error.message);
277
console.log("Location: Line", error.line, "Column", error.column);
278
console.log("Status:", error.status);
279
}
280
});
281
```