0
# Type Generation
1
2
Automatic TypeScript declaration generation system that creates type-safe interfaces for CSS module class names and handles class name transformations.
3
4
## Capabilities
5
6
### TypeScript Declaration Generation
7
8
Core system for generating TypeScript declarations from CSS modules.
9
10
```typescript { .api }
11
/**
12
* Creates TypeScript declaration snapshot for CSS files
13
* @param ts - TypeScript module reference
14
* @param processor - PostCSS processor instance
15
* @param fileName - CSS file path
16
* @param options - Plugin options
17
* @param logger - Logger instance
18
* @param compilerOptions - TypeScript compiler options
19
* @param directory - Project directory
20
* @returns TypeScript script snapshot
21
*/
22
function getDtsSnapshot(
23
ts: typeof tsModule,
24
processor: Processor,
25
fileName: string,
26
options: Options,
27
logger: Logger,
28
compilerOptions: tsModule.CompilerOptions,
29
directory: string
30
): tsModule.IScriptSnapshot;
31
```
32
33
**Generated Output Example:**
34
35
For a CSS file `component.module.css`:
36
37
```css
38
.header { color: blue; }
39
.nav-item { padding: 10px; }
40
.active { font-weight: bold; }
41
```
42
43
The plugin generates a TypeScript declaration:
44
45
```typescript
46
declare const styles: {
47
readonly header: string;
48
readonly "nav-item": string;
49
readonly navItem: string; // If camelCase transform enabled
50
readonly active: string;
51
};
52
export default styles;
53
54
// Named exports for valid identifiers
55
export const header: string;
56
export const active: string;
57
```
58
59
### Custom Template System
60
61
Extensible system for customizing TypeScript declaration generation.
62
63
```typescript { .api }
64
/**
65
* Custom template function type
66
*/
67
type CustomTemplate = (
68
dts: string,
69
options: CustomTemplateOptions
70
) => string;
71
72
/**
73
* Options passed to custom template functions
74
*/
75
interface CustomTemplateOptions {
76
/** Extracted CSS class names */
77
classes: CSSExports;
78
/** Current file being processed */
79
fileName: string;
80
/** Logger instance for debugging */
81
logger: Logger;
82
}
83
```
84
85
**Custom Template Implementation:**
86
87
```javascript
88
// customTemplate.js
89
module.exports = (dts, { classes, fileName, logger }) => {
90
try {
91
const classNames = Object.keys(classes);
92
93
// Generate custom declaration format
94
return `
95
declare module '${fileName}' {
96
interface Classes {
97
${classNames.map(name => `'${name}': string;`).join('\n ')}
98
}
99
100
const classes: Classes;
101
export default classes;
102
103
// Individual exports
104
${classNames.filter(name => /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name))
105
.map(name => `export const ${name}: string;`).join('\n ')}
106
}
107
`;
108
} catch (error) {
109
logger.error(error.message);
110
return dts; // Return original on error
111
}
112
};
113
```
114
115
**Configuration:**
116
117
```json
118
{
119
"compilerOptions": {
120
"plugins": [
121
{
122
"name": "typescript-plugin-css-modules",
123
"options": {
124
"customTemplate": "./customTemplate.js"
125
}
126
}
127
]
128
}
129
}
130
```
131
132
### DTS Export Creation
133
134
System for creating TypeScript declaration exports from CSS class names.
135
136
```typescript { .api }
137
/**
138
* Creates TypeScript declaration exports from CSS classes
139
* @param config - Export generation configuration
140
* @returns TypeScript declaration string
141
*/
142
function createDtsExports(config: {
143
cssExports: CSSExportsWithSourceMap;
144
fileName: string;
145
logger: Logger;
146
options: Options;
147
}): string;
148
```
149
150
**Generated Declaration Patterns:**
151
152
1. **Default Export** (always generated):
153
```typescript
154
declare const styles: {
155
readonly [className: string]: string;
156
};
157
export default styles;
158
```
159
160
2. **Named Exports** (when `namedExports: true`):
161
```typescript
162
export const validClassName: string;
163
export const anotherClass: string;
164
```
165
166
3. **Strict Typing** (when `noUncheckedIndexedAccess: true`):
167
```typescript
168
declare const styles: {
169
readonly className?: string;
170
readonly anotherClass?: string;
171
};
172
```
173
174
### Variable Name Validation
175
176
System for validating CSS class names as valid TypeScript identifiers.
177
178
```typescript { .api }
179
/**
180
* Regular expression for valid TypeScript variable names
181
*/
182
const VALID_VARIABLE_REGEXP: RegExp;
183
184
/**
185
* Checks if a class name can be used as a valid TypeScript identifier
186
* @param classname - CSS class name to validate
187
* @returns Boolean indicating if the name is valid
188
*/
189
function isValidVariable(classname: string): boolean;
190
```
191
192
**Validation Rules:**
193
194
- Must start with letter, underscore, or dollar sign
195
- Can contain letters, numbers, underscores, dollar signs
196
- Cannot be TypeScript reserved words
197
- Cannot contain hyphens or other special characters
198
199
**Examples:**
200
201
```typescript
202
// Valid identifiers (can be named exports)
203
isValidVariable('header') // true
204
isValidVariable('navItem') // true
205
isValidVariable('_private') // true
206
isValidVariable('$special') // true
207
208
// Invalid identifiers (default export only)
209
isValidVariable('nav-item') // false
210
isValidVariable('2nd-column') // false
211
isValidVariable('class') // false (reserved word)
212
```
213
214
### Class Name Processing
215
216
Advanced class name processing with transformation and validation.
217
218
```typescript { .api }
219
/**
220
* Flattens nested class name arrays into a single array
221
* @param previousValue - Accumulated class names
222
* @param currentValue - Current class name variants
223
* @returns Flattened array of class names
224
*/
225
function flattenClassNames(
226
previousValue?: string[],
227
currentValue?: string[]
228
): string[];
229
```
230
231
**Processing Pipeline:**
232
233
1. **Extract CSS Classes**: Parse CSS and extract all class names
234
2. **Apply Transformations**: Apply configured class name transformations
235
3. **Validate Identifiers**: Check which names can be used as TypeScript identifiers
236
4. **Generate Declarations**: Create TypeScript declaration string
237
5. **Create Snapshot**: Generate TypeScript script snapshot
238
239
### Source Map Integration
240
241
Support for source maps in generated TypeScript declarations for better debugging.
242
243
```typescript { .api }
244
/**
245
* Source map consumer for declaration generation
246
*/
247
interface SourceMapIntegration {
248
/** Raw source map data */
249
sourceMap?: RawSourceMap;
250
/** Source map consumer instance */
251
consumer?: SourceMapConsumer;
252
}
253
```
254
255
**Source Map Features:**
256
257
- **Go-to-definition**: Jump from TypeScript usage to CSS definition
258
- **Debugging support**: Maintain connection between generated types and source CSS
259
- **Error reporting**: Map TypeScript errors back to original CSS locations
260
261
### TypeScript Compatibility
262
263
Comprehensive compatibility with TypeScript compiler options and features.
264
265
```typescript { .api }
266
/**
267
* TypeScript compatibility options
268
*/
269
interface TypeScriptCompatibility {
270
/** Compatibility with noUncheckedIndexedAccess */
271
noUncheckedIndexedAccess?: boolean;
272
/** Allow unknown class names without warnings */
273
allowUnknownClassnames?: boolean;
274
/** Enable named exports for valid identifiers */
275
namedExports?: boolean;
276
}
277
```
278
279
**Compatibility Features:**
280
281
- **TypeScript 4.x and 5.x**: Full support for both TypeScript versions
282
- **Strict Mode**: Compatible with all TypeScript strict mode options
283
- **Module Resolution**: Supports all TypeScript module resolution strategies
284
- **Declaration Maps**: Generates source maps for better IDE integration
285
- **Type Checking**: Provides accurate type information for all CSS classes
286
287
### Error Handling
288
289
Comprehensive error handling for type generation edge cases:
290
291
- **Invalid CSS**: Graceful handling of malformed CSS files
292
- **Missing Files**: Error recovery when CSS files are not found
293
- **Type Conflicts**: Resolution of naming conflicts in generated types
294
- **Template Errors**: Error boundary for custom template failures
295
- **Source Map Errors**: Fallback when source maps cannot be generated
296
297
All errors include detailed context and suggestions for resolution.