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

file-matching.mddocs/

File Matching

File pattern matching system for identifying CSS module files and handling custom file extensions and naming conventions.

Capabilities

CSS File Detection

Core functions for identifying CSS module files based on configurable patterns.

/**
 * Function type for checking if a file is a CSS module
 */
type isCSSFn = (fileName: string) => boolean;

/**
 * Function type for checking if a file is a relative CSS module import
 */
type isRelativeCSSFn = (fileName: string) => boolean;

/**
 * Creates a CSS file checker function with optional custom pattern
 * @param customMatcher - Optional RegExp pattern for matching CSS files
 * @returns Function that checks if a filename matches CSS module pattern
 */
function createIsCSS(customMatcher?: RegExp): isCSSFn;

/**
 * Creates a relative CSS file checker function
 * @param isCSS - CSS file checker function
 * @returns Function that checks if a filename is a relative CSS import
 */
function createIsRelativeCSS(isCSS: isCSSFn): isRelativeCSSFn;

Default Pattern:

The default regular expression pattern is:

/\.module\.((c|le|sa|sc)ss|styl)$/

This matches files with the following patterns:

  • .module.css
  • .module.scss
  • .module.sass
  • .module.less
  • .module.styl

Usage Examples:

// Using default pattern
const isCSS = createIsCSS();
isCSS('component.module.css');    // true
isCSS('styles.module.scss');      // true
isCSS('theme.module.sass');       // true
isCSS('layout.module.less');      // true
isCSS('animations.module.styl');  // true
isCSS('regular.css');             // false
isCSS('script.js');               // false

// Using custom pattern
const customIsCSS = createIsCSS(/\.m\.(css|scss)$/);
customIsCSS('component.m.css');   // true
customIsCSS('styles.m.scss');     // true
customIsCSS('theme.module.css');  // false

Matcher Creation System

Factory system for creating file matchers with configuration and error handling.

/**
 * Matcher functions interface
 */
interface Matchers {
  /** Function to check if file is a CSS module */
  isCSS: isCSSFn;
  /** Function to check if file is a relative CSS module import */
  isRelativeCSS: isRelativeCSSFn;
}

/**
 * Creates matcher functions based on plugin options
 * @param logger - Logger instance for error reporting
 * @param options - Plugin options containing matcher configuration
 * @returns Object containing CSS file matcher functions
 */
function createMatchers(
  logger: Logger,
  options?: Options
): Matchers;

Configuration Examples:

  1. Default Configuration:
{
  "compilerOptions": {
    "plugins": [
      {
        "name": "typescript-plugin-css-modules"
      }
    ]
  }
}
  1. Custom Matcher Pattern:
{
  "compilerOptions": {
    "plugins": [
      {
        "name": "typescript-plugin-css-modules",
        "options": {
          "customMatcher": "\\.styles\\.(css|scss|sass)$"
        }
      }
    ]
  }
}
  1. Multiple File Extensions:
{
  "compilerOptions": {
    "plugins": [
      {
        "name": "typescript-plugin-css-modules",
        "options": {
          "customMatcher": "\\.(module|styles|theme)\\.(css|scss|sass|less|styl)$"
        }
      }
    ]
  }
}

Relative Import Detection

System for detecting relative CSS module imports to handle module resolution correctly.

/**
 * Checks if a file path is a relative import
 * @param fileName - File path to check
 * @returns Boolean indicating if the path is relative
 */
function isRelative(fileName: string): boolean;

Relative Import Patterns:

The system recognizes these patterns as relative imports:

  • ./component.module.css
  • ../shared/styles.module.scss
  • ./styles/theme.module.sass
  • ../../common/layout.module.less

Usage Examples:

const isCSS = createIsCSS();
const isRelativeCSS = createIsRelativeCSS(isCSS);

// Relative imports
isRelativeCSS('./component.module.css');     // true
isRelativeCSS('../styles/theme.module.scss'); // true

// Absolute imports  
isRelativeCSS('component.module.css');       // false
isRelativeCSS('styles/theme.module.scss');   // false

// Node modules
isRelativeCSS('some-package/styles.module.css'); // false

Error Handling and Validation

Robust error handling for invalid matcher patterns and configuration issues.

/**
 * Error handling for matcher creation
 */
interface MatcherErrorHandling {
  /** Validates regular expression patterns */
  validatePattern(pattern: string): boolean;
  /** Provides fallback matchers on error */
  createFallbackMatcher(): isCSSFn;
  /** Logs configuration warnings */
  logConfigurationWarnings(logger: Logger): void;
}

Error Scenarios:

  1. Invalid Regular Expression:
{
  "customMatcher": "[invalid regex pattern"
}

Result: Falls back to default pattern, logs error

  1. Empty Pattern:
{
  "customMatcher": ""
}

Result: Uses default pattern, logs warning

  1. Pattern Too Broad:
{
  "customMatcher": ".*"
}

Result: Works but logs performance warning

File Extension Support

Comprehensive support for various CSS preprocessor file extensions.

/**
 * Supported file extensions mapping
 */
interface FileExtensionSupport {
  /** Standard CSS files */
  css: string[];
  /** Sass files */
  sass: string[];
  /** SCSS files */
  scss: string[];
  /** Less files */
  less: string[];
  /** Stylus files */
  stylus: string[];
}

Supported Extensions:

  • CSS: .css
  • Sass: .sass
  • SCSS: .scss
  • Less: .less
  • Stylus: .styl

Pattern Examples for Different Use Cases:

  1. CSS Modules Only:
/\.module\.css$/
  1. SCSS Modules Only:
/\.module\.scss$/
  1. All Preprocessors:
/\.module\.((c|le|sa|sc)ss|styl)$/
  1. Custom Naming Convention:
/\.(styles|theme|components)\.css$/
  1. Scoped Styles:
/\.scoped\.(css|scss)$/

Module Resolution Integration

Integration with TypeScript's module resolution system for CSS modules.

/**
 * Module resolution for CSS files
 */
interface CSSModuleResolution {
  /** Resolves CSS module paths */
  resolveModulePath(moduleName: string, containingFile: string): string | undefined;
  /** Checks if module is external CSS library */
  isExternalCSSLibrary(moduleName: string): boolean;
  /** Handles failed module lookups */
  handleFailedLookup(moduleName: string, searchPaths: string[]): string | undefined;
}

Resolution Examples:

// Relative imports
import styles from './component.module.css';
// Resolves to: /project/src/components/component.module.css

// Parent directory imports  
import styles from '../shared/theme.module.scss';
// Resolves to: /project/src/shared/theme.module.scss

// Deep relative imports
import styles from '../../styles/global.module.css';
// Resolves to: /project/styles/global.module.css

Performance Optimization

Optimized file matching for large codebases with many CSS files.

/**
 * Performance optimization features
 */
interface PerformanceOptimization {
  /** Caches compiled regular expressions */
  cacheCompiledPatterns: boolean;
  /** Optimizes file system lookups */
  optimizeFileSystemAccess: boolean;
  /** Batches file matching operations */
  batchFileOperations: boolean;
}

Optimization Features:

  • Pattern Caching: Compiled regex patterns are cached to avoid recompilation
  • Early Exit: File extension check before regex matching for better performance
  • Batch Processing: Multiple files processed in single operations when possible
  • Lazy Loading: Matchers created only when needed

Integration with Build Tools

Compatibility with various build tools and development environments.

Webpack Integration:

  • Compatible with css-loader module naming conventions
  • Supports webpack's resolve.alias for CSS imports
  • Works with webpack-dev-server hot reloading

Vite Integration:

  • Supports Vite's CSS module conventions
  • Compatible with Vite's import.meta.glob patterns
  • Works with Vite's development server

Next.js Integration:

  • Compatible with Next.js CSS module conventions
  • Supports Next.js global styles exclusions
  • Works with Next.js app and pages directories

Create React App:

  • Works out of the box with CRA's CSS module setup
  • No additional configuration required
  • Compatible with CRA's build optimizations

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