A CSS parser, transformer, and minifier written in Rust with Node.js bindings
npx @tessl/cli install tessl/npm-lightningcss@1.30.00
# Lightning CSS
1
2
Lightning CSS is an extremely fast CSS parser, transformer, and minifier written in Rust that provides comprehensive CSS processing capabilities. It features typed property values, browser-grade parsing, extensive syntax lowering, and significant performance advantages over alternatives while producing smaller output files.
3
4
## Package Information
5
6
- **Package Name**: lightningcss
7
- **Package Type**: cargo (Rust) / npm (Node.js bindings)
8
- **Language**: Rust (with JavaScript/TypeScript bindings)
9
- **Installation**:
10
- Rust: `cargo add lightningcss`
11
- Node.js: `npm install lightningcss`
12
13
## Core Imports
14
15
**Node.js TypeScript/JavaScript:**
16
17
```typescript
18
import { transform, bundle, browserslistToTargets, Targets } from "lightningcss";
19
```
20
21
For CommonJS:
22
23
```javascript
24
const { transform, bundle, browserslistToTargets } = require("lightningcss");
25
```
26
27
**Rust:**
28
29
```rust
30
use lightningcss::{
31
stylesheet::{StyleSheet, MinifyOptions, ParserOptions, PrinterOptions},
32
targets::{Targets, Browsers},
33
bundler::Bundler,
34
};
35
```
36
37
## Basic Usage
38
39
**Node.js:**
40
41
```typescript
42
import { transform, Targets } from "lightningcss";
43
44
// Transform and minify CSS
45
const result = transform({
46
filename: "style.css",
47
code: new TextEncoder().encode(`
48
.example {
49
background-color: #ff0000;
50
border-radius: 5px;
51
}
52
`),
53
minify: true,
54
targets: {
55
chrome: 80 << 16,
56
firefox: 75 << 16,
57
}
58
});
59
60
console.log(new TextDecoder().decode(result.code));
61
```
62
63
**Rust:**
64
65
```rust
66
use lightningcss::{
67
stylesheet::{StyleSheet, MinifyOptions, ParserOptions, PrinterOptions},
68
targets::Targets,
69
};
70
71
// Parse and transform CSS
72
let mut stylesheet = StyleSheet::parse(
73
r#".example { background-color: #ff0000; border-radius: 5px; }"#,
74
ParserOptions::default(),
75
)?;
76
77
stylesheet.minify(MinifyOptions::default())?;
78
79
let result = stylesheet.to_css(PrinterOptions {
80
minify: true,
81
..PrinterOptions::default()
82
})?;
83
84
println!("{}", result.code);
85
```
86
87
## Architecture
88
89
Lightning CSS is built around several key components:
90
91
- **Parser**: Browser-grade CSS parsing using Mozilla's cssparser and selectors crates
92
- **Transformer**: Syntax lowering for modern CSS features with configurable browser targets
93
- **Minifier**: Safe optimization engine that preserves CSS behavior while reducing size
94
- **Bundler**: Dependency resolution and @import inlining with asset tracking
95
- **Multi-Interface**: Rust library, Node.js bindings, CLI tool, and build tool integrations
96
97
## Capabilities
98
99
### CSS Transformation
100
101
Core CSS parsing, transformation, and minification functionality with browser targeting and syntax lowering.
102
103
```typescript { .api }
104
function transform<C extends CustomAtRules>(
105
options: TransformOptions<C>
106
): TransformResult;
107
108
interface TransformOptions<C extends CustomAtRules> {
109
filename: string;
110
code: Uint8Array;
111
minify?: boolean;
112
sourceMap?: boolean;
113
inputSourceMap?: string;
114
projectRoot?: string;
115
targets?: Targets;
116
include?: number;
117
exclude?: number;
118
drafts?: Drafts;
119
nonStandard?: NonStandard;
120
cssModules?: boolean | CSSModulesConfig;
121
analyzeDependencies?: boolean | DependencyOptions;
122
pseudoClasses?: PseudoClasses;
123
unusedSymbols?: string[];
124
errorRecovery?: boolean;
125
visitor?: Visitor<C>;
126
customAtRules?: C;
127
}
128
129
interface TransformResult {
130
code: Uint8Array;
131
map: Uint8Array | void;
132
exports: CSSModuleExports | void;
133
references: CSSModuleReferences;
134
dependencies: Dependency[] | void;
135
warnings: Warning[];
136
}
137
```
138
139
[CSS Transformation](./transformation.md)
140
141
### CSS Bundling
142
143
Bundle CSS files with dependency resolution, @import inlining, and asset tracking for complete CSS processing pipelines.
144
145
```typescript { .api }
146
function bundle<C extends CustomAtRules>(
147
options: BundleOptions<C>
148
): TransformResult;
149
150
function bundleAsync<C extends CustomAtRules>(
151
options: BundleAsyncOptions<C>
152
): Promise<TransformResult>;
153
154
type BundleOptions<C extends CustomAtRules> = Omit<TransformOptions<C>, 'code'>;
155
156
interface BundleAsyncOptions<C extends CustomAtRules> extends BundleOptions<C> {
157
resolver?: Resolver;
158
}
159
```
160
161
[CSS Bundling](./bundling.md)
162
163
### Style Attribute Processing
164
165
Transform inline CSS style attributes with minification and dependency analysis for HTML processing.
166
167
```typescript { .api }
168
function transformStyleAttribute(
169
options: TransformAttributeOptions
170
): TransformAttributeResult;
171
172
interface TransformAttributeOptions {
173
filename?: string;
174
code: Uint8Array;
175
minify?: boolean;
176
targets?: Targets;
177
analyzeDependencies?: boolean;
178
errorRecovery?: boolean;
179
visitor?: Visitor<never>;
180
}
181
182
interface TransformAttributeResult {
183
code: Uint8Array;
184
dependencies: Dependency[] | void;
185
warnings: Warning[];
186
}
187
```
188
189
[Style Attributes](./style-attributes.md)
190
191
### Browser Targets
192
193
Browser compatibility targeting system for controlling CSS transformation and vendor prefixing.
194
195
```typescript { .api }
196
function browserslistToTargets(browserslist: string[]): Targets;
197
198
interface Targets {
199
android?: number;
200
chrome?: number;
201
edge?: number;
202
firefox?: number;
203
ie?: number;
204
ios_saf?: number;
205
opera?: number;
206
safari?: number;
207
samsung?: number;
208
}
209
```
210
211
[Browser Targets](./targets.md)
212
213
### AST Visitor System
214
215
Extensible AST visitor pattern for custom CSS transformations and analysis with type-safe interfaces.
216
217
```typescript { .api }
218
function composeVisitors<C extends CustomAtRules>(
219
visitors: Visitor<C>[]
220
): Visitor<C>;
221
222
interface Visitor<C extends CustomAtRules> {
223
StyleSheet?(stylesheet: StyleSheet): StyleSheet<ReturnedDeclaration, ReturnedMediaQuery> | void;
224
StyleSheetExit?(stylesheet: StyleSheet): StyleSheet<ReturnedDeclaration, ReturnedMediaQuery> | void;
225
Rule?: RuleVisitor | RuleVisitors<C>;
226
RuleExit?: RuleVisitor | RuleVisitors<C>;
227
Declaration?: DeclarationVisitor | DeclarationVisitors;
228
DeclarationExit?: DeclarationVisitor | DeclarationVisitors;
229
Url?(url: Url): Url | void;
230
Color?(color: CssColor): CssColor | void;
231
// ... additional visitor methods
232
}
233
```
234
235
[AST Visitors](./visitors.md)
236
237
### Rust Library API
238
239
Direct Rust library interface providing low-level CSS parsing, transformation, and serialization capabilities.
240
241
```rust { .api }
242
// StyleSheet parsing and transformation
243
impl<'i, 'o, T> StyleSheet<'i, 'o, T> {
244
pub fn parse(
245
css: &'i str,
246
options: ParserOptions<'o, 'i>
247
) -> Result<Self, Error<ParserError<'i>>>;
248
249
pub fn minify(&mut self, options: MinifyOptions) -> Result<(), Error<MinifyErrorKind>>;
250
251
pub fn to_css(&self, options: PrinterOptions) -> Result<ToCssResult, Error<PrinterErrorKind>>;
252
}
253
254
// Parser configuration
255
pub struct ParserOptions<'o, 'i> {
256
pub filename: &'i str,
257
pub css_modules: Option<CssModulesConfig<'o>>,
258
pub source_index: u32,
259
pub error_recovery: bool,
260
pub warnings: Option<&'o mut Vec<Error<ParserError<'i>>>>,
261
pub flags: ParserFlags,
262
}
263
```
264
265
[Rust API](./rust-api.md)
266
267
### Custom At-Rules
268
269
Define and process custom at-rules with configurable prelude syntax and body types for extending CSS with domain-specific functionality.
270
271
```typescript { .api }
272
interface CustomAtRules {
273
[name: string]: CustomAtRuleDefinition;
274
}
275
276
interface CustomAtRuleDefinition {
277
prelude?: SyntaxString | null;
278
body?: 'declaration-list' | 'rule-list' | 'style-block' | null;
279
}
280
281
type SyntaxString = `<${string}>` | `<${string}>+` | `<${string}>#` | (string & {});
282
```
283
284
Custom at-rules allow you to define parsing and processing behavior for non-standard CSS at-rules, enabling framework-specific extensions and custom CSS syntax.
285
286
## Types
287
288
```typescript { .api }
289
// Return types for visitor functions
290
type ReturnedDeclaration = Declaration | {
291
property: `${PropertyStart}${string}`;
292
raw: string;
293
};
294
295
type ReturnedMediaQuery = MediaQuery | {
296
raw: string;
297
};
298
299
// CSS Module types
300
interface CSSModulesConfig {
301
pattern?: string;
302
dashedIdents?: boolean;
303
animation?: boolean;
304
grid?: boolean;
305
container?: boolean;
306
customIdents?: boolean;
307
pure?: boolean;
308
}
309
310
interface CSSModuleExports {
311
[name: string]: CSSModuleExport;
312
}
313
314
interface CSSModuleExport {
315
name: string;
316
isReferenced: boolean;
317
composes: CSSModuleReference[];
318
}
319
320
type CSSModuleReferences = {
321
[name: string]: DependencyCSSModuleReference;
322
};
323
324
type CSSModuleReference = LocalCSSModuleReference | GlobalCSSModuleReference | DependencyCSSModuleReference;
325
326
interface LocalCSSModuleReference {
327
type: 'local';
328
name: string;
329
}
330
331
interface GlobalCSSModuleReference {
332
type: 'global';
333
name: string;
334
}
335
336
interface DependencyCSSModuleReference {
337
type: 'dependency';
338
name: string;
339
specifier: string;
340
}
341
342
// Custom At-Rules system
343
interface CustomAtRules {
344
[name: string]: CustomAtRuleDefinition;
345
}
346
347
interface CustomAtRuleDefinition {
348
prelude?: SyntaxString | null;
349
body?: 'declaration-list' | 'rule-list' | 'style-block' | null;
350
}
351
352
type SyntaxString = `<${string}>` | `<${string}>+` | `<${string}>#` | (string & {});
353
354
// Dependency types
355
type Dependency = ImportDependency | UrlDependency;
356
357
interface ImportDependency {
358
type: 'import';
359
url: string;
360
media: string | null;
361
supports: string | null;
362
loc: SourceLocation;
363
placeholder: string;
364
}
365
366
interface UrlDependency {
367
type: 'url';
368
url: string;
369
loc: SourceLocation;
370
placeholder: string;
371
}
372
373
// Location and error types
374
interface SourceLocation {
375
filePath: string;
376
start: Location;
377
end: Location;
378
}
379
380
interface Location {
381
line: number;
382
column: number;
383
}
384
385
interface ErrorLocation extends Location {
386
filename: string;
387
}
388
389
// Configuration types
390
interface Drafts {
391
customMedia?: boolean;
392
}
393
394
interface NonStandard {
395
deepSelectorCombinator?: boolean;
396
}
397
398
interface PseudoClasses {
399
hover?: string;
400
active?: string;
401
focus?: string;
402
focusVisible?: string;
403
focusWithin?: string;
404
}
405
406
interface DependencyOptions {
407
preserveImports?: boolean;
408
}
409
410
// Raw value type for visitor returns
411
interface RawValue {
412
raw: string;
413
}
414
415
// Token visitor types
416
type VisitableTokenTypes = 'ident' | 'at-keyword' | 'hash' | 'id-hash' | 'string' | 'number' | 'percentage' | 'dimension';
417
418
type TokenReturnValue = TokenOrValue | TokenOrValue[] | RawValue | void;
419
420
// Warning and error types
421
interface Warning {
422
message: string;
423
type: string;
424
value?: any;
425
loc: ErrorLocation;
426
}
427
```