0
# CSS Transformation
1
2
Core CSS parsing, transformation, and minification functionality with browser targeting, syntax lowering, and comprehensive optimization capabilities.
3
4
## Capabilities
5
6
### Transform Function
7
8
Processes CSS files with optional minification, syntax lowering, vendor prefixing, and dependency analysis.
9
10
```typescript { .api }
11
/**
12
* Compiles a CSS file, including optionally minifying and lowering syntax to the given targets
13
* @param options - Transformation configuration options
14
* @returns Transformation result with code, source map, exports, and dependencies
15
*/
16
function transform<C extends CustomAtRules>(
17
options: TransformOptions<C>
18
): TransformResult;
19
20
interface TransformOptions<C extends CustomAtRules> {
21
/** The filename being transformed. Used for error messages and source maps. */
22
filename: string;
23
/** The source code to transform. */
24
code: Uint8Array;
25
/** Whether to enable minification. */
26
minify?: boolean;
27
/** Whether to output a source map. */
28
sourceMap?: boolean;
29
/** An input source map to extend. */
30
inputSourceMap?: string;
31
/**
32
* An optional project root path, used as the source root in the output source map.
33
* Also used to generate relative paths for sources used in CSS module hashes.
34
*/
35
projectRoot?: string;
36
/** The browser targets for the generated code. */
37
targets?: Targets;
38
/** Features that should always be compiled, even when supported by targets. */
39
include?: number;
40
/** Features that should never be compiled, even when unsupported by targets. */
41
exclude?: number;
42
/** Whether to enable parsing various draft syntax. */
43
drafts?: Drafts;
44
/** Whether to enable various non-standard syntax. */
45
nonStandard?: NonStandard;
46
/** Whether to compile this file as a CSS module. */
47
cssModules?: boolean | CSSModulesConfig;
48
/**
49
* Whether to analyze dependencies (e.g. `@import` and `url()`).
50
* When enabled, `@import` rules are removed, and `url()` dependencies
51
* are replaced with hashed placeholders that can be replaced with the final
52
* urls later (after bundling). Dependencies are returned as part of the result.
53
*/
54
analyzeDependencies?: boolean | DependencyOptions;
55
/**
56
* Replaces user action pseudo classes with class names that can be applied from JavaScript.
57
* This is useful for polyfills, for example.
58
*/
59
pseudoClasses?: PseudoClasses;
60
/**
61
* A list of class names, ids, and custom identifiers (e.g. @keyframes) that are known
62
* to be unused. These will be removed during minification. Note that these are not
63
* selectors but individual names (without any . or # prefixes).
64
*/
65
unusedSymbols?: string[];
66
/**
67
* Whether to ignore invalid rules and declarations rather than erroring.
68
* When enabled, warnings are returned, and the invalid rule or declaration is
69
* omitted from the output code.
70
*/
71
errorRecovery?: boolean;
72
/**
73
* An AST visitor object. This allows custom transforms or analysis to be implemented in JavaScript.
74
* Multiple visitors can be composed into one using the `composeVisitors` function.
75
* For optimal performance, visitors should be as specific as possible about what types of values
76
* they care about so that JavaScript has to be called as little as possible.
77
*/
78
visitor?: Visitor<C>;
79
/**
80
* Defines how to parse custom CSS at-rules. Each at-rule can have a prelude, defined using a CSS
81
* syntax string, and a block body. The body can be a declaration list, rule list, or style block.
82
*/
83
customAtRules?: C;
84
}
85
86
interface TransformResult {
87
/** The transformed code. */
88
code: Uint8Array;
89
/** The generated source map, if enabled. */
90
map: Uint8Array | void;
91
/** CSS module exports, if enabled. */
92
exports: CSSModuleExports | void;
93
/** CSS module references, if `dashedIdents` is enabled. */
94
references: CSSModuleReferences;
95
/** `@import` and `url()` dependencies, if enabled. */
96
dependencies: Dependency[] | void;
97
/** Warnings that occurred during compilation. */
98
warnings: Warning[];
99
}
100
```
101
102
**Usage Examples:**
103
104
```typescript
105
import { transform, browserslistToTargets } from "lightningcss";
106
107
// Basic transformation with minification
108
const result = transform({
109
filename: "styles.css",
110
code: new TextEncoder().encode(`
111
.button {
112
background-color: #ff0000;
113
border-radius: 8px;
114
transition: all 0.2s ease;
115
}
116
117
.button:hover {
118
background-color: #cc0000;
119
}
120
`),
121
minify: true
122
});
123
124
console.log(new TextDecoder().decode(result.code));
125
126
// Transformation with browser targets
127
const modernResult = transform({
128
filename: "modern.css",
129
code: new TextEncoder().encode(`
130
.container {
131
display: grid;
132
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
133
gap: 1rem;
134
color: lab(50% 20 -30);
135
}
136
`),
137
targets: browserslistToTargets(['last 2 versions']),
138
minify: true
139
});
140
141
// CSS Modules transformation
142
const moduleResult = transform({
143
filename: "component.module.css",
144
code: new TextEncoder().encode(`
145
.title {
146
font-size: 2rem;
147
color: blue;
148
}
149
150
.subtitle {
151
composes: title;
152
font-size: 1.5rem;
153
}
154
`),
155
cssModules: {
156
pattern: '[name]_[local]_[hash]',
157
dashedIdents: true
158
}
159
});
160
161
console.log(moduleResult.exports); // CSS module class mappings
162
```
163
164
### Draft CSS Features
165
166
Enable parsing of CSS features that are still in draft status.
167
168
```typescript { .api }
169
interface Drafts {
170
/** Whether to enable @custom-media rules. */
171
customMedia?: boolean;
172
}
173
```
174
175
**Usage Example:**
176
177
```typescript
178
const result = transform({
179
filename: "drafts.css",
180
code: new TextEncoder().encode(`
181
@custom-media --small-viewport (max-width: 30em);
182
183
@media (--small-viewport) {
184
.responsive { font-size: 14px; }
185
}
186
`),
187
drafts: {
188
customMedia: true
189
}
190
});
191
```
192
193
### Non-Standard CSS Features
194
195
Enable parsing of non-standard CSS syntax used by frameworks.
196
197
```typescript { .api }
198
interface NonStandard {
199
/** Whether to enable the non-standard >>> and /deep/ selector combinators used by Angular and Vue. */
200
deepSelectorCombinator?: boolean;
201
}
202
```
203
204
**Usage Example:**
205
206
```typescript
207
const result = transform({
208
filename: "vue-component.css",
209
code: new TextEncoder().encode(`
210
.component >>> .child {
211
color: red;
212
}
213
214
.component /deep/ .deep-child {
215
background: blue;
216
}
217
`),
218
nonStandard: {
219
deepSelectorCombinator: true
220
}
221
});
222
```
223
224
### Pseudo-Class Replacement
225
226
Replace user action pseudo-classes with class names for JavaScript polyfills.
227
228
```typescript { .api }
229
interface PseudoClasses {
230
hover?: string;
231
active?: string;
232
focus?: string;
233
focusVisible?: string;
234
focusWithin?: string;
235
}
236
```
237
238
**Usage Example:**
239
240
```typescript
241
const result = transform({
242
filename: "polyfill.css",
243
code: new TextEncoder().encode(`
244
.button:hover { background: blue; }
245
.input:focus { border-color: green; }
246
.card:focus-visible { outline: 2px solid orange; }
247
`),
248
pseudoClasses: {
249
hover: 'is-hovered',
250
focus: 'is-focused',
251
focusVisible: 'is-focus-visible'
252
}
253
});
254
255
// Result transforms :hover to .is-hovered, etc.
256
```
257
258
### Unused Symbol Removal
259
260
Remove unused CSS symbols during minification for smaller output.
261
262
```typescript { .api }
263
// unusedSymbols parameter in TransformOptions
264
unusedSymbols?: string[];
265
```
266
267
**Usage Example:**
268
269
```typescript
270
const result = transform({
271
filename: "app.css",
272
code: new TextEncoder().encode(`
273
.used-class { color: red; }
274
.unused-class { color: blue; }
275
276
@keyframes used-animation { 0% { opacity: 0; } }
277
@keyframes unused-animation { 0% { opacity: 1; } }
278
`),
279
minify: true,
280
unusedSymbols: ['unused-class', 'unused-animation']
281
});
282
// Unused symbols will be removed from the output
283
```
284
285
### Error Recovery
286
287
Continue processing CSS even when invalid syntax is encountered.
288
289
```typescript { .api }
290
// errorRecovery parameter in TransformOptions
291
errorRecovery?: boolean;
292
```
293
294
**Usage Example:**
295
296
```typescript
297
const result = transform({
298
filename: "broken.css",
299
code: new TextEncoder().encode(`
300
.valid { color: red; }
301
.invalid { invalid-property: bad-value; }
302
.also-valid { background: blue; }
303
`),
304
errorRecovery: true
305
});
306
307
console.log(result.warnings); // Contains warnings for invalid syntax
308
// Valid rules are still processed and included in output
309
```