0
# Advanced Features
1
2
Advanced features for CSS processing, modules generation, PostCSS integration, and custom transformations.
3
4
## Capabilities
5
6
### CSS Processing Pipeline
7
8
Custom CSS processor function for advanced transformations like PostCSS integration, autoprefixing, and CSS modules.
9
10
```typescript { .api }
11
/**
12
* Custom CSS processor function for advanced transformations
13
* @param styles - Compiled CSS string
14
* @param id - File path/ID of the processed file
15
* @returns Processed CSS string or object with css and additional exports
16
*/
17
type RollupPluginSassProcessorFn<T = RollupPluginSassProcessorFnOutput> =
18
(styles: string, id: string) => Promise<T> | T;
19
20
type RollupPluginSassProcessorFnOutput =
21
| string
22
| {
23
css: string;
24
cssModules?: Record<string, string>;
25
[key: string]: unknown;
26
};
27
```
28
29
**Usage Examples:**
30
31
```typescript
32
import sass from 'rollup-plugin-sass';
33
import postcss from 'postcss';
34
import autoprefixer from 'autoprefixer';
35
36
// PostCSS integration
37
sass({
38
processor: async (css, id) => {
39
const result = await postcss([autoprefixer])
40
.process(css, { from: id });
41
return result.css;
42
},
43
});
44
45
// Multiple PostCSS plugins
46
sass({
47
processor: async (css, id) => {
48
const result = await postcss([
49
autoprefixer(),
50
require('cssnano')({ preset: 'default' }),
51
]).process(css, { from: id });
52
return result.css;
53
},
54
});
55
```
56
57
### CSS Modules Generation
58
59
Generate CSS modules by returning `cssModules` object from processor function.
60
61
```typescript { .api }
62
interface CSSModulesOutput {
63
/** Processed CSS string */
64
css: string;
65
/** CSS modules mapping object that becomes the default export */
66
cssModules?: Record<string, string>;
67
/** Additional named exports */
68
[key: string]: unknown;
69
}
70
```
71
72
**Usage Examples:**
73
74
```typescript
75
import sass from 'rollup-plugin-sass';
76
import postcss from 'postcss';
77
import postcssModules from 'postcss-modules';
78
79
// CSS Modules with postcss-modules
80
sass({
81
processor: async (css, id) => {
82
let cssModules = {};
83
84
const result = await postcss([
85
postcssModules({
86
getJSON: (_, json) => {
87
if (json) cssModules = json;
88
},
89
}),
90
]).process(css, { from: id });
91
92
return {
93
css: result.css,
94
cssModules,
95
};
96
},
97
});
98
```
99
100
Then in your JavaScript:
101
102
```typescript
103
import styles from './component.scss';
104
105
// styles is now the CSS modules object
106
console.log(styles.className); // "component_className_abc123"
107
```
108
109
### Named Exports from Processor
110
111
Create additional named exports alongside the default CSS export.
112
113
```typescript { .api }
114
interface ProcessorWithExports {
115
css: string;
116
/** Additional named exports available via import { exportName } */
117
[exportName: string]: unknown;
118
}
119
```
120
121
**Usage Examples:**
122
123
```typescript
124
sass({
125
processor: (css, id) => {
126
return {
127
css: css,
128
theme: 'dark',
129
version: '1.0.0',
130
breakpoints: {
131
mobile: '768px',
132
tablet: '1024px',
133
},
134
};
135
},
136
});
137
```
138
139
Usage in JavaScript:
140
141
```typescript
142
import styles, { theme, version, breakpoints } from './styles.scss';
143
```
144
145
### ICSS Exports (Sass Variables to JavaScript)
146
147
Extract Sass variables and make them available as JavaScript exports using icss-utils.
148
149
**Usage Examples:**
150
151
```typescript
152
import sass from 'rollup-plugin-sass';
153
import postcss from 'postcss';
154
import { extractICSS } from 'icss-utils';
155
156
sass({
157
processor: (css) => {
158
const pcssRoot = postcss.parse(css);
159
const extractedIcss = extractICSS(pcssRoot, true);
160
const cleanedCss = pcssRoot.toString();
161
162
return {
163
css: cleanedCss,
164
...extractedIcss.icssExports,
165
};
166
},
167
});
168
```
169
170
With Sass file containing:
171
172
```scss
173
:export {
174
primaryColor: #007bff;
175
fontSize: 16px;
176
}
177
178
.button {
179
color: $primary-color;
180
font-size: $font-size;
181
}
182
```
183
184
Available in JavaScript:
185
186
```typescript
187
import styles, { primaryColor, fontSize } from './styles.scss';
188
```
189
190
### Node Modules Import Resolution
191
192
Built-in support for importing Sass files from node_modules using `~` syntax.
193
194
```typescript { .api }
195
interface ImporterSupport {
196
/** Legacy API importer for node_modules resolution */
197
getImporterListLegacy: (
198
importOption: LegacyImporter<'async'> | LegacyImporter<'async'>[]
199
) => LegacyImporter<'async'>[];
200
201
/** Modern API importer for node_modules resolution */
202
getImporterListModern: (
203
importOption: FileImporter<'async'>[]
204
) => FileImporter<'async'>[];
205
}
206
```
207
208
**Usage Examples:**
209
210
```scss
211
// Import from node_modules
212
@import '~bootstrap/scss/bootstrap';
213
@import '~normalize.css/normalize';
214
215
// Import local files normally
216
@import './variables';
217
@import '../components/button';
218
```
219
220
### Style Injection Utility
221
222
Client-side utility function for injecting styles into the document head.
223
224
```typescript { .api }
225
/**
226
* Creates and appends style tag to document head (browser-side utility)
227
* @param css - CSS string to inject
228
* @returns The injected CSS string or undefined if no CSS or not in browser
229
*/
230
function insertStyle(css: string | undefined): string | undefined;
231
```
232
233
This function is automatically included when using `insert: true` option:
234
235
```typescript
236
sass({
237
insert: true, // Automatically includes insertStyle utility
238
});
239
```
240
241
### Custom Output Handling
242
243
Advanced output control with detailed style node information.
244
245
```typescript { .api }
246
/**
247
* Custom output handler with access to individual style nodes
248
* @param styles - Concatenated CSS string
249
* @param styleNodes - Array of individual style objects with metadata
250
*/
251
type RollupPluginSassOutputFn = (
252
styles: string,
253
styleNodes: StyleSheetIdAndContent[]
254
) => unknown;
255
256
interface StyleSheetIdAndContent {
257
/** File path/ID of the style */
258
id?: string;
259
/** Compiled CSS content */
260
content?: string;
261
}
262
```
263
264
**Usage Examples:**
265
266
```typescript
267
sass({
268
output(styles, styleNodes) {
269
// Write concatenated styles
270
writeFileSync('all-styles.css', styles);
271
272
// Write individual style files
273
styleNodes.forEach((node) => {
274
if (node.id && node.content) {
275
const filename = path.basename(node.id, path.extname(node.id)) + '.css';
276
writeFileSync(`dist/individual/${filename}`, node.content);
277
}
278
});
279
280
// Generate style manifest
281
const manifest = {
282
totalSize: styles.length,
283
fileCount: styleNodes.length,
284
files: styleNodes.map(node => ({
285
id: node.id,
286
size: node.content?.length || 0,
287
})),
288
};
289
290
writeFileSync('style-manifest.json', JSON.stringify(manifest, null, 2));
291
},
292
});
293
```
294
295
## Complete Advanced Example
296
297
```typescript
298
import sass from 'rollup-plugin-sass';
299
import postcss from 'postcss';
300
import autoprefixer from 'autoprefixer';
301
import postcssModules from 'postcss-modules';
302
import cssnano from 'cssnano';
303
304
export default {
305
input: 'src/index.js',
306
output: {
307
file: 'dist/bundle.js',
308
format: 'esm',
309
},
310
plugins: [
311
sass({
312
api: 'modern',
313
include: ['src/**/*.scss'],
314
315
// Advanced processor with CSS modules and PostCSS
316
processor: async (css, id) => {
317
let cssModules = {};
318
319
const result = await postcss([
320
postcssModules({
321
getJSON: (_, json) => {
322
if (json) cssModules = json;
323
},
324
}),
325
autoprefixer(),
326
cssnano({ preset: 'default' }),
327
]).process(css, { from: id });
328
329
return {
330
css: result.css,
331
cssModules,
332
processedAt: new Date().toISOString(),
333
};
334
},
335
336
// Custom output with detailed logging
337
output(styles, styleNodes) {
338
console.log(`Generated ${styleNodes.length} style files`);
339
console.log(`Total CSS size: ${styles.length} characters`);
340
341
writeFileSync('dist/styles.css', styles);
342
343
// Generate source map of style files
344
const sourceMap = styleNodes.map(node => ({
345
source: node.id,
346
size: node.content?.length || 0,
347
}));
348
349
writeFileSync('dist/style-sources.json', JSON.stringify(sourceMap, null, 2));
350
},
351
352
options: {
353
style: 'compressed',
354
loadPaths: ['node_modules'],
355
data: '@import "theme-variables";',
356
},
357
}),
358
],
359
};
360
```