or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

bundling.mdindex.mdrust-api.mdstyle-attributes.mdtargets.mdtransformation.mdvisitors.md
tile.json

tessl/npm-lightningcss

A CSS parser, transformer, and minifier written in Rust with Node.js bindings

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/lightningcss@1.30.x

To install, run

npx @tessl/cli install tessl/npm-lightningcss@1.30.0

index.mddocs/

Lightning CSS

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.

Package Information

  • Package Name: lightningcss
  • Package Type: cargo (Rust) / npm (Node.js bindings)
  • Language: Rust (with JavaScript/TypeScript bindings)
  • Installation:
    • Rust: cargo add lightningcss
    • Node.js: npm install lightningcss

Core Imports

Node.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,
};

Basic Usage

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);

Architecture

Lightning CSS is built around several key components:

  • Parser: Browser-grade CSS parsing using Mozilla's cssparser and selectors crates
  • Transformer: Syntax lowering for modern CSS features with configurable browser targets
  • Minifier: Safe optimization engine that preserves CSS behavior while reducing size
  • Bundler: Dependency resolution and @import inlining with asset tracking
  • Multi-Interface: Rust library, Node.js bindings, CLI tool, and build tool integrations

Capabilities

CSS Transformation

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[];
}

CSS Transformation

CSS Bundling

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;
}

CSS Bundling

Style Attribute Processing

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[];
}

Style Attributes

Browser Targets

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;
}

Browser Targets

AST Visitor System

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
}

AST Visitors

Rust Library API

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,
}

Rust API

Custom At-Rules

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.

Types

// 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;
}