A CSS parser, transformer, and minifier written in Rust with Node.js bindings
npx @tessl/cli install tessl/npm-lightningcss@1.30.0Lightning 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.
cargo add lightningcssnpm install lightningcssNode.js TypeScript/JavaScript:
import { transform, bundle, browserslistToTargets, Targets } from "lightningcss";For CommonJS:
const { transform, bundle, browserslistToTargets } = require("lightningcss");Rust:
use lightningcss::{
stylesheet::{StyleSheet, MinifyOptions, ParserOptions, PrinterOptions},
targets::{Targets, Browsers},
bundler::Bundler,
};Node.js:
import { transform, Targets } from "lightningcss";
// Transform and minify CSS
const result = transform({
filename: "style.css",
code: new TextEncoder().encode(`
.example {
background-color: #ff0000;
border-radius: 5px;
}
`),
minify: true,
targets: {
chrome: 80 << 16,
firefox: 75 << 16,
}
});
console.log(new TextDecoder().decode(result.code));Rust:
use lightningcss::{
stylesheet::{StyleSheet, MinifyOptions, ParserOptions, PrinterOptions},
targets::Targets,
};
// Parse and transform CSS
let mut stylesheet = StyleSheet::parse(
r#".example { background-color: #ff0000; border-radius: 5px; }"#,
ParserOptions::default(),
)?;
stylesheet.minify(MinifyOptions::default())?;
let result = stylesheet.to_css(PrinterOptions {
minify: true,
..PrinterOptions::default()
})?;
println!("{}", result.code);Lightning CSS is built around several key components:
Core CSS parsing, transformation, and minification functionality with browser targeting and syntax lowering.
function transform<C extends CustomAtRules>(
options: TransformOptions<C>
): TransformResult;
interface TransformOptions<C extends CustomAtRules> {
filename: string;
code: Uint8Array;
minify?: boolean;
sourceMap?: boolean;
inputSourceMap?: string;
projectRoot?: string;
targets?: Targets;
include?: number;
exclude?: number;
drafts?: Drafts;
nonStandard?: NonStandard;
cssModules?: boolean | CSSModulesConfig;
analyzeDependencies?: boolean | DependencyOptions;
pseudoClasses?: PseudoClasses;
unusedSymbols?: string[];
errorRecovery?: boolean;
visitor?: Visitor<C>;
customAtRules?: C;
}
interface TransformResult {
code: Uint8Array;
map: Uint8Array | void;
exports: CSSModuleExports | void;
references: CSSModuleReferences;
dependencies: Dependency[] | void;
warnings: Warning[];
}Bundle CSS files with dependency resolution, @import inlining, and asset tracking for complete CSS processing pipelines.
function bundle<C extends CustomAtRules>(
options: BundleOptions<C>
): TransformResult;
function bundleAsync<C extends CustomAtRules>(
options: BundleAsyncOptions<C>
): Promise<TransformResult>;
type BundleOptions<C extends CustomAtRules> = Omit<TransformOptions<C>, 'code'>;
interface BundleAsyncOptions<C extends CustomAtRules> extends BundleOptions<C> {
resolver?: Resolver;
}Transform inline CSS style attributes with minification and dependency analysis for HTML processing.
function transformStyleAttribute(
options: TransformAttributeOptions
): TransformAttributeResult;
interface TransformAttributeOptions {
filename?: string;
code: Uint8Array;
minify?: boolean;
targets?: Targets;
analyzeDependencies?: boolean;
errorRecovery?: boolean;
visitor?: Visitor<never>;
}
interface TransformAttributeResult {
code: Uint8Array;
dependencies: Dependency[] | void;
warnings: Warning[];
}Browser compatibility targeting system for controlling CSS transformation and vendor prefixing.
function browserslistToTargets(browserslist: string[]): Targets;
interface Targets {
android?: number;
chrome?: number;
edge?: number;
firefox?: number;
ie?: number;
ios_saf?: number;
opera?: number;
safari?: number;
samsung?: number;
}Extensible AST visitor pattern for custom CSS transformations and analysis with type-safe interfaces.
function composeVisitors<C extends CustomAtRules>(
visitors: Visitor<C>[]
): Visitor<C>;
interface Visitor<C extends CustomAtRules> {
StyleSheet?(stylesheet: StyleSheet): StyleSheet<ReturnedDeclaration, ReturnedMediaQuery> | void;
StyleSheetExit?(stylesheet: StyleSheet): StyleSheet<ReturnedDeclaration, ReturnedMediaQuery> | void;
Rule?: RuleVisitor | RuleVisitors<C>;
RuleExit?: RuleVisitor | RuleVisitors<C>;
Declaration?: DeclarationVisitor | DeclarationVisitors;
DeclarationExit?: DeclarationVisitor | DeclarationVisitors;
Url?(url: Url): Url | void;
Color?(color: CssColor): CssColor | void;
// ... additional visitor methods
}Direct Rust library interface providing low-level CSS parsing, transformation, and serialization capabilities.
// StyleSheet parsing and transformation
impl<'i, 'o, T> StyleSheet<'i, 'o, T> {
pub fn parse(
css: &'i str,
options: ParserOptions<'o, 'i>
) -> Result<Self, Error<ParserError<'i>>>;
pub fn minify(&mut self, options: MinifyOptions) -> Result<(), Error<MinifyErrorKind>>;
pub fn to_css(&self, options: PrinterOptions) -> Result<ToCssResult, Error<PrinterErrorKind>>;
}
// Parser configuration
pub struct ParserOptions<'o, 'i> {
pub filename: &'i str,
pub css_modules: Option<CssModulesConfig<'o>>,
pub source_index: u32,
pub error_recovery: bool,
pub warnings: Option<&'o mut Vec<Error<ParserError<'i>>>>,
pub flags: ParserFlags,
}Define and process custom at-rules with configurable prelude syntax and body types for extending CSS with domain-specific functionality.
interface CustomAtRules {
[name: string]: CustomAtRuleDefinition;
}
interface CustomAtRuleDefinition {
prelude?: SyntaxString | null;
body?: 'declaration-list' | 'rule-list' | 'style-block' | null;
}
type SyntaxString = `<${string}>` | `<${string}>+` | `<${string}>#` | (string & {});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.
// Return types for visitor functions
type ReturnedDeclaration = Declaration | {
property: `${PropertyStart}${string}`;
raw: string;
};
type ReturnedMediaQuery = MediaQuery | {
raw: string;
};
// CSS Module types
interface CSSModulesConfig {
pattern?: string;
dashedIdents?: boolean;
animation?: boolean;
grid?: boolean;
container?: boolean;
customIdents?: boolean;
pure?: boolean;
}
interface CSSModuleExports {
[name: string]: CSSModuleExport;
}
interface CSSModuleExport {
name: string;
isReferenced: boolean;
composes: CSSModuleReference[];
}
type CSSModuleReferences = {
[name: string]: DependencyCSSModuleReference;
};
type CSSModuleReference = LocalCSSModuleReference | GlobalCSSModuleReference | DependencyCSSModuleReference;
interface LocalCSSModuleReference {
type: 'local';
name: string;
}
interface GlobalCSSModuleReference {
type: 'global';
name: string;
}
interface DependencyCSSModuleReference {
type: 'dependency';
name: string;
specifier: string;
}
// Custom At-Rules system
interface CustomAtRules {
[name: string]: CustomAtRuleDefinition;
}
interface CustomAtRuleDefinition {
prelude?: SyntaxString | null;
body?: 'declaration-list' | 'rule-list' | 'style-block' | null;
}
type SyntaxString = `<${string}>` | `<${string}>+` | `<${string}>#` | (string & {});
// Dependency types
type Dependency = ImportDependency | UrlDependency;
interface ImportDependency {
type: 'import';
url: string;
media: string | null;
supports: string | null;
loc: SourceLocation;
placeholder: string;
}
interface UrlDependency {
type: 'url';
url: string;
loc: SourceLocation;
placeholder: string;
}
// Location and error types
interface SourceLocation {
filePath: string;
start: Location;
end: Location;
}
interface Location {
line: number;
column: number;
}
interface ErrorLocation extends Location {
filename: string;
}
// Configuration types
interface Drafts {
customMedia?: boolean;
}
interface NonStandard {
deepSelectorCombinator?: boolean;
}
interface PseudoClasses {
hover?: string;
active?: string;
focus?: string;
focusVisible?: string;
focusWithin?: string;
}
interface DependencyOptions {
preserveImports?: boolean;
}
// Raw value type for visitor returns
interface RawValue {
raw: string;
}
// Token visitor types
type VisitableTokenTypes = 'ident' | 'at-keyword' | 'hash' | 'id-hash' | 'string' | 'number' | 'percentage' | 'dimension';
type TokenReturnValue = TokenOrValue | TokenOrValue[] | RawValue | void;
// Warning and error types
interface Warning {
message: string;
type: string;
value?: any;
loc: ErrorLocation;
}