or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

config.mdextraction.mdgenerator.mdindex.mdrules-variants.mdtypes.mdutilities.md

generator.mddocs/

0

# Generator and CSS Generation

1

2

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.

3

4

## Generator Creation

5

6

```typescript { .api }

7

function createGenerator<Theme extends object = object>(

8

config?: UserConfig<Theme>,

9

defaults?: UserConfigDefaults<Theme>

10

): Promise<UnoGenerator<Theme>>;

11

```

12

13

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

14

15

**Parameters:**

16

- `config`: User configuration object containing rules, variants, theme, etc.

17

- `defaults`: Default configuration values that serve as fallbacks

18

19

**Returns:** Promise resolving to a `UnoGenerator` instance

20

21

## UnoGenerator Class

22

23

```typescript { .api }

24

class UnoGenerator<Theme extends object = object> {

25

readonly version: string;

26

readonly config: ResolvedConfig<Theme>;

27

readonly cache: Map<string, StringifiedUtil<Theme>[] | null>;

28

readonly blocked: Set<string>;

29

readonly activatedRules: Set<Rule<Theme>>;

30

readonly events: Emitter<{ config: (config: ResolvedConfig<Theme>) => void }>;

31

32

/** @deprecated Use createGenerator() instead */

33

constructor(userConfig?: UserConfig<Theme>, defaults?: UserConfigDefaults<Theme>);

34

35

generate(

36

input: string | Set<string> | CountableSet<string> | string[],

37

options?: GenerateOptions<false>

38

): Promise<GenerateResult<Set<string>>>;

39

generate(

40

input: string | Set<string> | CountableSet<string> | string[],

41

options?: GenerateOptions<true>

42

): Promise<GenerateResult<Map<string, ExtendedTokenInfo<Theme>>>>;

43

44

setConfig(

45

userConfig?: UserConfig<Theme>,

46

defaults?: UserConfigDefaults<Theme>

47

): Promise<void>;

48

49

applyExtractors(

50

code: string,

51

id?: string,

52

extracted?: Set<string>

53

): Promise<Set<string>>;

54

applyExtractors(

55

code: string,

56

id?: string,

57

extracted?: CountableSet<string>

58

): Promise<CountableSet<string>>;

59

60

parseToken(

61

raw: string,

62

alias?: string

63

): Promise<StringifiedUtil<Theme>[] | undefined | null>;

64

65

matchVariants(

66

raw: string,

67

current?: string

68

): Promise<readonly VariantMatchedResult<Theme>[]>;

69

}

70

```

71

72

## Control Symbols

73

74

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

75

76

```typescript { .api }

77

const symbols: ControlSymbols = {

78

shortcutsNoMerge: typeof SymbolShortcutsNoMerge;

79

noMerge: typeof SymbolNoMerge;

80

variants: typeof SymbolVariants;

81

parent: typeof SymbolParent;

82

selector: typeof SymbolSelector;

83

layer: typeof SymbolLayer;

84

sort: typeof SymbolSort;

85

body: typeof SymbolBody;

86

};

87

```

88

89

## Utility Functions

90

91

Utility functions exported from the generator module for CSS processing.

92

93

```typescript { .api }

94

function toEscapedSelector(raw: string): string;

95

function hasScopePlaceholder(css: string): boolean;

96

```

97

98

**Functions:**

99

- **toEscapedSelector**: Converts utility class name to escaped CSS selector

100

- **hasScopePlaceholder**: Checks if CSS string contains scope placeholders

101

102

## CSS Generation

103

104

### Basic Generation

105

106

```typescript

107

// Generate CSS from string input

108

const result = await uno.generate('text-red-500 bg-blue-100 hover:opacity-50');

109

console.log(result.css);

110

// Output: .text-red-500{color:rgb(239 68 68);}.bg-blue-100{background-color:rgb(219 234 254);}...

111

112

// Generate from array of classes

113

const result = await uno.generate(['m-4', 'p-2', 'text-center']);

114

115

// Generate from Set

116

const classes = new Set(['flex', 'items-center', 'justify-between']);

117

const result = await uno.generate(classes);

118

```

119

120

### Generation Options

121

122

```typescript { .api }

123

interface GenerateOptions<T extends boolean> {

124

id?: string;

125

preflights?: boolean;

126

safelist?: boolean;

127

minify?: boolean;

128

scope?: string;

129

extendedInfo?: T;

130

}

131

132

interface GenerateResult<T = Set<string>> {

133

css: string;

134

layers: string[];

135

matched: T;

136

getLayer: (name?: string) => string | undefined;

137

getLayers: (includes?: string[], excludes?: string[]) => string;

138

setLayer: (layer: string, callback: (content: string) => Promise<string>) => Promise<string>;

139

}

140

```

141

142

**GenerateOptions properties:**

143

- `id`: Filepath identifier for the content being processed

144

- `preflights`: Whether to include preflight CSS (default: `true`)

145

- `safelist`: Whether to include safelist utilities (default: `true`)

146

- `minify`: Generate minified CSS without line breaks (default: `false`)

147

- `scope`: Scope selector to prefix all generated CSS

148

- `extendedInfo`: Return extended information about matched tokens

149

150

## Content Extraction

151

152

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

153

154

```typescript

155

// Extract classes from source code

156

const extracted = await uno.applyExtractors(`

157

<div class="flex items-center p-4">

158

<h1 class="text-xl font-bold">Hello</h1>

159

</div>

160

`, 'component.html');

161

162

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

163

```

164

165

## Token Parsing

166

167

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

168

169

```typescript

170

// Parse a single token

171

const parsed = await uno.parseToken('text-red-500');

172

console.log(parsed); // Array of StringifiedUtil objects

173

174

// Parse with alias

175

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

176

```

177

178

## Variant Matching

179

180

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

181

182

```typescript

183

// Match variants on a utility

184

const variants = await uno.matchVariants('hover:focus:text-red-500');

185

console.log(variants); // Array of VariantMatchedResult objects

186

```

187

188

## Configuration Updates

189

190

Generator configuration can be updated at runtime:

191

192

```typescript

193

// Update generator configuration

194

await uno.setConfig({

195

rules: [

196

...existingRules,

197

['new-rule', { 'new-property': 'value' }]

198

]

199

});

200

201

// Configuration changes trigger cache clearing and re-resolution

202

```

203

204

## Events

205

206

The generator provides events for configuration changes:

207

208

```typescript

209

// Listen for config changes

210

const unsubscribe = uno.events.on('config', (config) => {

211

console.log('Config updated:', config);

212

});

213

214

// Cleanup listener

215

unsubscribe();

216

```

217

218

## Performance Considerations

219

220

- **Caching**: The generator maintains internal caches for parsed tokens and CSS generation

221

- **Incremental Updates**: Only changed configuration triggers cache invalidation

222

- **Lazy Evaluation**: CSS generation is performed on-demand

223

- **Efficient Matching**: Static rules use hash maps for O(1) lookup, dynamic rules use optimized regex matching