CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-unocss--core

The core atomic CSS engine for UnoCSS that generates CSS on-demand without any presets or default utilities.

Pending
Overview
Eval results
Files

generator.mddocs/

Generator and CSS Generation

The UnoCSS Core generator is the main engine that orchestrates CSS generation from utility classes. It handles rule matching, variant processing, caching, and CSS output optimization.

Generator Creation

function createGenerator<Theme extends object = object>(
  config?: UserConfig<Theme>,
  defaults?: UserConfigDefaults<Theme>
): Promise<UnoGenerator<Theme>>;

Creates a new UnoCSS generator instance. The generator is asynchronously created to allow for config resolution and preset loading.

Parameters:

  • config: User configuration object containing rules, variants, theme, etc.
  • defaults: Default configuration values that serve as fallbacks

Returns: Promise resolving to a UnoGenerator instance

UnoGenerator Class

class UnoGenerator<Theme extends object = object> {
  readonly version: string;
  readonly config: ResolvedConfig<Theme>;
  readonly cache: Map<string, StringifiedUtil<Theme>[] | null>;
  readonly blocked: Set<string>;
  readonly activatedRules: Set<Rule<Theme>>;
  readonly events: Emitter<{ config: (config: ResolvedConfig<Theme>) => void }>;

  /** @deprecated Use createGenerator() instead */
  constructor(userConfig?: UserConfig<Theme>, defaults?: UserConfigDefaults<Theme>);

  generate(
    input: string | Set<string> | CountableSet<string> | string[],
    options?: GenerateOptions<false>
  ): Promise<GenerateResult<Set<string>>>;
  generate(
    input: string | Set<string> | CountableSet<string> | string[],
    options?: GenerateOptions<true>
  ): Promise<GenerateResult<Map<string, ExtendedTokenInfo<Theme>>>>;

  setConfig(
    userConfig?: UserConfig<Theme>,
    defaults?: UserConfigDefaults<Theme>
  ): Promise<void>;

  applyExtractors(
    code: string,
    id?: string,
    extracted?: Set<string>
  ): Promise<Set<string>>;
  applyExtractors(
    code: string,
    id?: string,
    extracted?: CountableSet<string>
  ): Promise<CountableSet<string>>;

  parseToken(
    raw: string,
    alias?: string
  ): Promise<StringifiedUtil<Theme>[] | undefined | null>;

  matchVariants(
    raw: string,
    current?: string
  ): Promise<readonly VariantMatchedResult<Theme>[]>;
}

Control Symbols

Special symbols used for CSS manipulation and control within rules and shortcuts.

const symbols: ControlSymbols = {
  shortcutsNoMerge: typeof SymbolShortcutsNoMerge;
  noMerge: typeof SymbolNoMerge;
  variants: typeof SymbolVariants;
  parent: typeof SymbolParent;
  selector: typeof SymbolSelector;
  layer: typeof SymbolLayer;
  sort: typeof SymbolSort;
  body: typeof SymbolBody;
};

Utility Functions

Utility functions exported from the generator module for CSS processing.

function toEscapedSelector(raw: string): string;
function hasScopePlaceholder(css: string): boolean;

Functions:

  • toEscapedSelector: Converts utility class name to escaped CSS selector
  • hasScopePlaceholder: Checks if CSS string contains scope placeholders

CSS Generation

Basic Generation

// Generate CSS from string input
const result = await uno.generate('text-red-500 bg-blue-100 hover:opacity-50');
console.log(result.css);
// Output: .text-red-500{color:rgb(239 68 68);}.bg-blue-100{background-color:rgb(219 234 254);}...

// Generate from array of classes
const result = await uno.generate(['m-4', 'p-2', 'text-center']);

// Generate from Set
const classes = new Set(['flex', 'items-center', 'justify-between']);
const result = await uno.generate(classes);

Generation Options

interface GenerateOptions<T extends boolean> {
  id?: string;
  preflights?: boolean;
  safelist?: boolean;
  minify?: boolean;
  scope?: string;
  extendedInfo?: T;
}

interface GenerateResult<T = Set<string>> {
  css: string;
  layers: string[];
  matched: T;
  getLayer: (name?: string) => string | undefined;
  getLayers: (includes?: string[], excludes?: string[]) => string;
  setLayer: (layer: string, callback: (content: string) => Promise<string>) => Promise<string>;
}

GenerateOptions properties:

  • id: Filepath identifier for the content being processed
  • preflights: Whether to include preflight CSS (default: true)
  • safelist: Whether to include safelist utilities (default: true)
  • minify: Generate minified CSS without line breaks (default: false)
  • scope: Scope selector to prefix all generated CSS
  • extendedInfo: Return extended information about matched tokens

Content Extraction

The generator can extract utility classes from source code using configured extractors:

// Extract classes from source code
const extracted = await uno.applyExtractors(`
  <div class="flex items-center p-4">
    <h1 class="text-xl font-bold">Hello</h1>
  </div>
`, 'component.html');

console.log(extracted); // Set { 'flex', 'items-center', 'p-4', 'text-xl', 'font-bold' }

Token Parsing

Individual utility tokens can be parsed to understand their CSS generation:

// Parse a single token
const parsed = await uno.parseToken('text-red-500');
console.log(parsed); // Array of StringifiedUtil objects

// Parse with alias
const parsed = await uno.parseToken('text-red-500', 'text-danger');

Variant Matching

The generator can match variants (modifiers) on utility classes:

// Match variants on a utility
const variants = await uno.matchVariants('hover:focus:text-red-500');
console.log(variants); // Array of VariantMatchedResult objects

Configuration Updates

Generator configuration can be updated at runtime:

// Update generator configuration
await uno.setConfig({
  rules: [
    ...existingRules,
    ['new-rule', { 'new-property': 'value' }]
  ]
});

// Configuration changes trigger cache clearing and re-resolution

Events

The generator provides events for configuration changes:

// Listen for config changes
const unsubscribe = uno.events.on('config', (config) => {
  console.log('Config updated:', config);
});

// Cleanup listener
unsubscribe();

Performance Considerations

  • Caching: The generator maintains internal caches for parsed tokens and CSS generation
  • Incremental Updates: Only changed configuration triggers cache invalidation
  • Lazy Evaluation: CSS generation is performed on-demand
  • Efficient Matching: Static rules use hash maps for O(1) lookup, dynamic rules use optimized regex matching

Install with Tessl CLI

npx tessl i tessl/npm-unocss--core

docs

config.md

extraction.md

generator.md

index.md

rules-variants.md

types.md

utilities.md

tile.json