lightningcss

package module
v0.0.0-...-175d8b7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 26, 2026 License: MPL-2.0 Imports: 7 Imported by: 0

README

go-lightningcss

Go bindings for LightningCSS.

This library wraps a WebAssembly build of LightningCSS transpiled to Go using wasm2go.

[!WARNING]

These bindings are still experimental and are subject to change. They also produce extremely large binaries and are slow to compile.

Getting started
res, err := lightningcss.Transform(`...`, &lightningcss.Options{
    Filename: "style.css",
    Minify:   true,
    Nesting:  true,
    Targets: lightningcss.Targets{
        Chrome: lightningcss.Version(95, 0, 0),
        Safari: lightningcss.Version(14, 0, 0),
    },
    SourceMap: true,
})
if err != nil {
    panic(err)
}
for _, w := range res.Warnings {
    fmt.Fprintln(os.Stderr, "warning:", w)
}
fmt.Printf("%s\n", res.Code)
Design

Most LightningCSS functionality is exposed. All errors are handled appropriately and returned.

Concurrency

The package is safe for concurrent use since each call instantiates its own temporary copy of the module.

Testing

The generated code should be reproducible, but I haven't fully verified it (I'm yet familiar enough with Rust to fully verify it).

The CSS output will be identical to other LightningCSS bindings.

Building

The transpiled code is very large, and compiling it takes a LOT of memory. Currently, it takes ~12 GB of RAM to build on an 8-core machine with Go 1.26.2. This appears to be mostly because the cost for Go's optimizer is super-linear to the function size and runs concurrently. The memory usage also increases with the total size of the package, which is quite large.

You can set GOMAXPROCS to a lower value when building to reduce the memory usage significantly, though it will stail take multiple gigabytes.

You can also set -gcflags=all='-N -l' to disable optimizations, which reduces the memory a bit more at the cost of slower, bloated (multi-gigabyte) binaries.

If you're building on a smaller machine, I recommend using something like systemd-run --user --scope -p MemoryMax=12G -p MemorySwapMax=0 to ensure you don't accidentally OOM your session.

As long as the wasm2go blob isn't modified, future builds should be nearly instant due to caching.

This overhead is only for compiling. Although the resulting binary is about 10x the size of the WebAssembly, the memory usage at runtime is reasonable.

Documentation

Overview

Package lightningcss provides Go bindings for LightningCSS.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Minify

func Minify(css []byte) ([]byte, error)

Minify minifies css leniently. It is identical to calling Transform with Options.Minify.

func Version

func Version(major, minor, patch uint8) uint32

Version encodes a browser version as expected by Targets.

Types

type CSSModuleExport

type CSSModuleExport struct {
	// Name is the compiled (scoped) name.
	Name string
	// Composes lists other names this export composes, in order.
	Composes []CSSModuleReference
	// IsReferenced reports whether the export is referenced within the module.
	IsReferenced bool
}

CSSModuleExport is a single exported identifier from a CSS module.

type CSSModuleReference

type CSSModuleReference struct {
	// Type is "local", "global", or "dependency".
	Type string
	// Name is the referenced name.
	Name string
	// Specifier is the module specifier the name is referenced from (dependency
	// references only).
	Specifier string
}

CSSModuleReference is a reference from one CSS module export to another.

type CSSModules

type CSSModules struct {
	// Pattern is the naming pattern for scoped names, e.g. "[hash]_[local]" or
	// "[path][name]_[local]". If empty, the default pattern is used.
	Pattern string
	// DashedIdents scopes variables prefixed with "--" as well.
	DashedIdents bool
	// Pure requires class/id selectors in every rule (CSS Modules "pure" mode).
	Pure bool
	// Animation, Grid, CustomIdents, and Container scope the respective kinds
	// of identifiers. They default to true. Set a pointer to false to disable
	// one.
	Animation    *bool
	Grid         *bool
	CustomIdents *bool
	Container    *bool
}

CSSModules configures CSS modules compilation. Class names and other identifiers are scoped, and the mapping is returned in Result.Exports.

type Dependency

type Dependency struct {
	// Type is "import" or "url".
	Type string
	// URL is the referenced URL.
	URL string
	// Placeholder is the unique string substituted into the output for this
	// dependency.
	Placeholder string
	// Supports is the value of the @import supports() condition, if any (import
	// dependencies only).
	Supports string
	// Media is the media query of the @import, if any (import dependencies
	// only).
	Media string
	// Loc is the source location of the dependency.
	Loc SourceRange
}

Dependency is an `@import` or `url()` reference discovered when Options.AnalyzeDependencies is enabled. The original reference is replaced in the output with Placeholder, which callers can substitute after resolving.

type Location

type Location struct {
	Line   uint32
	Column uint32
}

Location is a 1-based line/column position.

type Options

type Options struct {
	// Filename is the source file name, used in error messages, source maps,
	// and CSS modules name hashing.
	Filename string

	// Minify removes whitespace and other redundancy from the output.
	// Regardless of this setting, lightningcss always normalizes values and,
	// when Targets is set, lowers modern syntax and adds vendor prefixes.
	Minify bool

	// Targets sets the minimum browser versions to support. See [Targets].
	Targets Targets

	// ErrorRecovery continues past most parse and minify errors, emitting them
	// as warnings (see [Result.Warnings]) instead of failing.
	ErrorRecovery bool

	// Nesting enables parsing of CSS nesting.
	Nesting bool

	// CustomMedia enables parsing of @custom-media rules.
	CustomMedia bool

	// DeepSelectorCombinator enables parsing of the non-standard >>> and /deep/
	// combinators.
	DeepSelectorCombinator bool

	// UnusedSymbols is a set of class names, ids, @keyframes names, CSS
	// variables, and other identifiers to remove from the output.
	UnusedSymbols []string

	// CSSModules, if non-nil, enables CSS modules compilation.
	CSSModules *CSSModules

	// PseudoClasses, if non-nil, substitutes user-action pseudo-classes with
	// regular classes.
	PseudoClasses *PseudoClasses

	// AnalyzeDependencies replaces @import and url() references with
	// placeholders and reports them in [Result.Dependencies].
	AnalyzeDependencies bool

	// RemoveImports removes @import rules when AnalyzeDependencies is set (they
	// are expected to be handled by the caller's bundler).
	RemoveImports bool

	// SourceMap generates a source map, returned in [Result.Map].
	SourceMap bool

	// InputSourceMap is an existing source map (JSON) for the input that the
	// generated source map should extend. Only used when SourceMap is set.
	InputSourceMap []byte

	// ProjectRoot is the root directory used to make source map paths relative.
	ProjectRoot string

	// StyleAttribute parses the input as the value of an inline style attribute
	// (a declaration list) rather than a full stylesheet.
	StyleAttribute bool
}

Options configures a CSS transformation. The zero value is valid and parses, minimally normalizes, and pretty-prints the input.

type PseudoClasses

type PseudoClasses struct {
	Hover        string
	Active       string
	Focus        string
	FocusVisible string
	FocusWithin  string
}

PseudoClasses replaces user-action pseudo-classes with regular classes so that states can be forced for testing or screenshots. Each field, if non-empty, is the class name to substitute for that pseudo-class.

type Result

type Result struct {
	// Code is the transformed CSS.
	Code []byte

	// Map is the generated source map (JSON), or nil if Options.SourceMap was
	// not set.
	Map []byte

	// Exports maps the original to the compiled identifiers when CSS modules
	// are enabled.
	Exports map[string]CSSModuleExport

	// References maps placeholders to CSS module references when CSS modules
	// are enabled.
	References map[string]CSSModuleReference

	// Dependencies lists @import and url() references when
	// Options.AnalyzeDependencies is set.
	Dependencies []Dependency

	// Warnings lists non-fatal diagnostics produced during parsing and
	// minifying.
	Warnings []string
}

Result is the output of a transformation.

func Transform

func Transform(css []byte, opts *Options) (*Result, error)

Transform parses, transforms, and serializes css.

type SourceRange

type SourceRange struct {
	FilePath string
	Start    Location
	End      Location
}

SourceRange is a span in the source file.

type Targets

type Targets struct {
	Android   uint32
	Chrome    uint32
	Edge      uint32
	Firefox   uint32
	IE        uint32
	IOSSafari uint32
	Opera     uint32
	Safari    uint32
	Samsung   uint32
}

Targets specifies the minimum browser versions to compile CSS syntax for. Each value is an encoded version number: (major << 16) | (minor << 8) | patch. A zero value means the browser is not targeted. Use Version to construct an encoded value.

When any target is set, lightningcss compiles modern syntax (nesting, custom media, color functions, logical properties, etc.) and adds vendor prefixes as needed so the output works in the targeted browsers.

func (Targets) IsZero

func (t Targets) IsZero() bool

IsZero reports whether no targets are set.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL