CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-typescript-plugin-css-modules

CSS modules support for TypeScript language service providing intelligent type information and auto-completion for CSS module imports

Pending
Overview
Eval results
Files

type-generation.mddocs/

Type Generation

Automatic TypeScript declaration generation system that creates type-safe interfaces for CSS module class names and handles class name transformations.

Capabilities

TypeScript Declaration Generation

Core system for generating TypeScript declarations from CSS modules.

/**
 * Creates TypeScript declaration snapshot for CSS files
 * @param ts - TypeScript module reference
 * @param processor - PostCSS processor instance
 * @param fileName - CSS file path
 * @param options - Plugin options
 * @param logger - Logger instance
 * @param compilerOptions - TypeScript compiler options
 * @param directory - Project directory
 * @returns TypeScript script snapshot
 */
function getDtsSnapshot(
  ts: typeof tsModule,
  processor: Processor,
  fileName: string,
  options: Options,
  logger: Logger,
  compilerOptions: tsModule.CompilerOptions,
  directory: string
): tsModule.IScriptSnapshot;

Generated Output Example:

For a CSS file component.module.css:

.header { color: blue; }
.nav-item { padding: 10px; }
.active { font-weight: bold; }

The plugin generates a TypeScript declaration:

declare const styles: {
  readonly header: string;
  readonly "nav-item": string;
  readonly navItem: string; // If camelCase transform enabled
  readonly active: string;
};
export default styles;

// Named exports for valid identifiers
export const header: string;
export const active: string;

Custom Template System

Extensible system for customizing TypeScript declaration generation.

/**
 * Custom template function type
 */
type CustomTemplate = (
  dts: string,
  options: CustomTemplateOptions
) => string;

/**
 * Options passed to custom template functions
 */
interface CustomTemplateOptions {
  /** Extracted CSS class names */
  classes: CSSExports;
  /** Current file being processed */
  fileName: string;
  /** Logger instance for debugging */
  logger: Logger;
}

Custom Template Implementation:

// customTemplate.js
module.exports = (dts, { classes, fileName, logger }) => {
  try {
    const classNames = Object.keys(classes);
    
    // Generate custom declaration format
    return `
declare module '${fileName}' {
  interface Classes {
    ${classNames.map(name => `'${name}': string;`).join('\n    ')}
  }
  
  const classes: Classes;
  export default classes;
  
  // Individual exports
  ${classNames.filter(name => /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name))
    .map(name => `export const ${name}: string;`).join('\n  ')}
}
`;
  } catch (error) {
    logger.error(error.message);
    return dts; // Return original on error
  }
};

Configuration:

{
  "compilerOptions": {
    "plugins": [
      {
        "name": "typescript-plugin-css-modules",
        "options": {
          "customTemplate": "./customTemplate.js"
        }
      }
    ]
  }
}

DTS Export Creation

System for creating TypeScript declaration exports from CSS class names.

/**
 * Creates TypeScript declaration exports from CSS classes
 * @param config - Export generation configuration
 * @returns TypeScript declaration string
 */
function createDtsExports(config: {
  cssExports: CSSExportsWithSourceMap;
  fileName: string;
  logger: Logger;
  options: Options;
}): string;

Generated Declaration Patterns:

  1. Default Export (always generated):
declare const styles: {
  readonly [className: string]: string;
};
export default styles;
  1. Named Exports (when namedExports: true):
export const validClassName: string;
export const anotherClass: string;
  1. Strict Typing (when noUncheckedIndexedAccess: true):
declare const styles: {
  readonly className?: string;
  readonly anotherClass?: string;
};

Variable Name Validation

System for validating CSS class names as valid TypeScript identifiers.

/**
 * Regular expression for valid TypeScript variable names
 */
const VALID_VARIABLE_REGEXP: RegExp;

/**
 * Checks if a class name can be used as a valid TypeScript identifier
 * @param classname - CSS class name to validate
 * @returns Boolean indicating if the name is valid
 */
function isValidVariable(classname: string): boolean;

Validation Rules:

  • Must start with letter, underscore, or dollar sign
  • Can contain letters, numbers, underscores, dollar signs
  • Cannot be TypeScript reserved words
  • Cannot contain hyphens or other special characters

Examples:

// Valid identifiers (can be named exports)
isValidVariable('header') // true
isValidVariable('navItem') // true
isValidVariable('_private') // true
isValidVariable('$special') // true

// Invalid identifiers (default export only)
isValidVariable('nav-item') // false
isValidVariable('2nd-column') // false
isValidVariable('class') // false (reserved word)

Class Name Processing

Advanced class name processing with transformation and validation.

/**
 * Flattens nested class name arrays into a single array
 * @param previousValue - Accumulated class names
 * @param currentValue - Current class name variants
 * @returns Flattened array of class names
 */
function flattenClassNames(
  previousValue?: string[],
  currentValue?: string[]
): string[];

Processing Pipeline:

  1. Extract CSS Classes: Parse CSS and extract all class names
  2. Apply Transformations: Apply configured class name transformations
  3. Validate Identifiers: Check which names can be used as TypeScript identifiers
  4. Generate Declarations: Create TypeScript declaration string
  5. Create Snapshot: Generate TypeScript script snapshot

Source Map Integration

Support for source maps in generated TypeScript declarations for better debugging.

/**
 * Source map consumer for declaration generation
 */
interface SourceMapIntegration {
  /** Raw source map data */
  sourceMap?: RawSourceMap;
  /** Source map consumer instance */
  consumer?: SourceMapConsumer;
}

Source Map Features:

  • Go-to-definition: Jump from TypeScript usage to CSS definition
  • Debugging support: Maintain connection between generated types and source CSS
  • Error reporting: Map TypeScript errors back to original CSS locations

TypeScript Compatibility

Comprehensive compatibility with TypeScript compiler options and features.

/**
 * TypeScript compatibility options
 */
interface TypeScriptCompatibility {
  /** Compatibility with noUncheckedIndexedAccess */
  noUncheckedIndexedAccess?: boolean;
  /** Allow unknown class names without warnings */
  allowUnknownClassnames?: boolean;
  /** Enable named exports for valid identifiers */
  namedExports?: boolean;
}

Compatibility Features:

  • TypeScript 4.x and 5.x: Full support for both TypeScript versions
  • Strict Mode: Compatible with all TypeScript strict mode options
  • Module Resolution: Supports all TypeScript module resolution strategies
  • Declaration Maps: Generates source maps for better IDE integration
  • Type Checking: Provides accurate type information for all CSS classes

Error Handling

Comprehensive error handling for type generation edge cases:

  • Invalid CSS: Graceful handling of malformed CSS files
  • Missing Files: Error recovery when CSS files are not found
  • Type Conflicts: Resolution of naming conflicts in generated types
  • Template Errors: Error boundary for custom template failures
  • Source Map Errors: Fallback when source maps cannot be generated

All errors include detailed context and suggestions for resolution.

Install with Tessl CLI

npx tessl i tessl/npm-typescript-plugin-css-modules

docs

css-processing.md

file-matching.md

index.md

plugin-configuration.md

type-generation.md

tile.json