or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-parcel--transformer-css

CSS transformer plugin for Parcel bundler that processes CSS files using LightningCSS

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@parcel/transformer-css@2.15.x

To install, run

npx @tessl/cli install tessl/npm-parcel--transformer-css@2.15.0

index.mddocs/

@parcel/transformer-css

@parcel/transformer-css is a CSS transformer plugin for the Parcel bundler that provides comprehensive CSS processing capabilities using LightningCSS. It handles CSS transformation, CSS modules support, dependency analysis, source map generation, and browser compatibility transformations with advanced features like error recovery and asset environment normalization.

Package Information

  • Package Name: @parcel/transformer-css
  • Package Type: npm
  • Language: JavaScript (with Flow types)
  • Installation: Automatically included with Parcel 2.x installations
  • Parcel Version: ^2.15.3
  • Node Version: >= 16.0.0

Core Imports

This is a Parcel plugin that exports a configured Transformer instance and is not typically imported directly by user code. The transformer is automatically used by Parcel when processing CSS files.

// For custom Parcel configurations or plugin development
const CSSTransformer = require("@parcel/transformer-css");

Basic Usage

The transformer operates automatically within Parcel's build pipeline when CSS files are encountered. Configuration is provided through .parcelrc or package.json:

{
  "@parcel/transformer-css": {
    "cssModules": {
      "include": ["**/*.module.css"],
      "exclude": ["**/node_modules/**"]
    },
    "errorRecovery": false,
    "drafts": {},
    "pseudoClasses": {}
  }
}

Architecture

The transformer is built around several key components:

  • LightningCSS Integration: Uses LightningCSS for high-performance CSS parsing and transformation
  • CSS Modules Engine: Configurable CSS modules processing with include/exclude patterns
  • Dependency Analysis: Automatic detection and processing of CSS imports and URL dependencies
  • Asset Environment Normalization: Normalizes asset environments for consistent bundling across different output formats
  • Source Map Integration: Preserves and generates source maps throughout the transformation process
  • Error Recovery System: Configurable error recovery with detailed diagnostic reporting

Capabilities

CSS Processing and Transformation

Core CSS transformation functionality that processes standard CSS files with browser compatibility transformations.

/**
 * Main CSS transformation method
 * @param {Object} params - Transformation parameters
 * @param {Asset} params.asset - Parcel asset to transform
 * @param {Object} params.config - Transformer configuration
 * @param {Object} params.options - Build options
 * @param {Logger} params.logger - Parcel logger instance
 * @returns {Promise<Asset[]>} Array of transformed assets
 */
async function transform({ asset, config, options, logger }): Promise<Asset[]>;

CSS Modules Processing

Processes CSS files as CSS modules with configurable include/exclude patterns and advanced features.

/**
 * CSS Modules configuration interface
 */
interface CSSModulesConfig {
  /** Enable CSS modules globally or with specific configuration */
  cssModules?: boolean | {
    /** Glob patterns for files to process as CSS modules */
    include?: string | string[] | RegExp[];
    /** Glob patterns for files to exclude from CSS module processing */
    exclude?: string | string[] | RegExp[];
    /** Process all CSS files as modules when true */
    global?: boolean;
    /** Support dashed identifiers in CSS modules */
    dashedIdents?: boolean;
  };
}

Style Attribute Processing

Transforms CSS within HTML style attributes with dependency analysis.

/**
 * Processes inline CSS within HTML style attributes
 * Uses LightningCSS transformStyleAttribute function
 * Automatically applied when asset.meta.type === 'attr'
 */

Configuration Loading

Loads and processes transformer configuration with glob pattern conversion.

/**
 * Configuration loader method
 * @param {Object} params - Configuration parameters
 * @param {Config} params.config - Parcel config instance
 * @param {Object} params.options - Build options
 * @returns {Promise<Object>} Processed configuration
 */
async function loadConfig({ config, options }): Promise<Object>;

Dependency Analysis

Automatically detects and processes CSS imports and URL dependencies.

/**
 * Dependency types handled by the transformer
 */
interface CSSDependency {
  type: 'import' | 'url';
  url: string;
  loc: SourceLocation;
  media?: string;
  placeholder?: string;
}

Browser Target Configuration

Converts browserslist configurations to LightningCSS targets with caching.

/**
 * Converts browserslist to LightningCSS targets
 * @param {string} browsers - Browserslist query string
 * @returns {Object|undefined} LightningCSS targets or undefined
 */
function getTargets(browsers: string): Object | undefined;

Source Location Conversion

Converts between LightningCSS and Parcel source location formats.

/**
 * Source location interfaces
 */
interface SourceLocation {
  filePath: string;
  start: { line: number; column: number };
  end: { line: number; column: number };
}

/**
 * Converts LightningCSS source location to Parcel format
 * @param {LightningSourceLocation} loc - LightningCSS source location
 * @returns {SourceLocation} Parcel source location
 */
function convertLoc(loc: LightningSourceLocation): SourceLocation;

Configuration Options

CSS Modules Configuration

interface CSSModulesOptions {
  /** Enable CSS modules processing (boolean or detailed config) */
  cssModules?: boolean | {
    /** Files to include as CSS modules (glob patterns or RegExp) */
    include?: string | string[] | RegExp[];
    /** Files to exclude from CSS modules (glob patterns or RegExp) */
    exclude?: string | string[] | RegExp[];
    /** Enable CSS modules globally */
    global?: boolean;
    /** Support dashed identifiers */
    dashedIdents?: boolean;
  };
}

CSS Processing Options

interface CSSProcessingOptions {
  /** Enable error recovery during CSS parsing */
  errorRecovery?: boolean;
  /** CSS draft features configuration */
  drafts?: Object;
  /** CSS pseudo-classes configuration */
  pseudoClasses?: Object;
}

Error Handling

Diagnostic Integration

The transformer integrates with Parcel's diagnostic system for comprehensive error reporting.

/**
 * Error handling with diagnostic conversion
 * Automatically converts LightningCSS errors to Parcel diagnostics
 * Provides helpful hints for common issues like ambiguous URLs
 */
interface DiagnosticError {
  message: string;
  filePath: string;
  codeFrames?: CodeFrame[];
  hints?: string[];
  documentationURL?: string;
}

interface CodeFrame {
  filePath: string;
  codeHighlights: CodeHighlight[];
}

interface CodeHighlight {
  start: { line: number; column: number };
  end: { line: number; column: number };
}

Warning Processing

Processes and logs LightningCSS warnings with source location information.

/**
 * Warning interface from LightningCSS
 */
interface LightningWarning {
  message: string;
  loc: {
    line: number;
    column: number;
  };
}

Asset Types

Supported Asset Types

The transformer handles multiple types of CSS assets based on metadata:

/**
 * Asset types processed by the transformer
 */
type AssetType = 
  | 'default'    // Standard CSS files
  | 'module'     // CSS module files  
  | 'attr'       // CSS within HTML style attributes
  | 'tag';       // CSS within tagged templates

Asset Environment Normalization

Normalizes asset environments for consistent bundling across different output formats.

/**
 * Normalized asset environment properties
 */
interface NormalizedEnvironment {
  context: 'browser' | 'react-client';
  engines: {
    browsers: string;
  };
  shouldOptimize: boolean;
  shouldScopeHoist: boolean;
  sourceMap: boolean;
}

Dependencies

Core Dependencies

/**
 * Key dependencies used by the transformer
 */
interface TransformerDependencies {
  /** LightningCSS for CSS processing */
  lightningcss: {
    transform: Function;
    transformStyleAttribute: Function;
    browserslistToTargets: Function;
  };
  /** Parcel utilities */
  '@parcel/utils': {
    remapSourceLocation: Function;
    relativePath: Function;
    globToRegex: Function;
    normalizeSeparators: Function;
  };
  /** Browserslist for browser targeting */
  browserslist: Function;
}

Parcel Core Types

/**
 * Core Parcel types used by the transformer
 * These are simplified interfaces - full definitions are in @parcel/* packages
 */
interface Asset {
  filePath: string;
  env: AssetEnvironment;
  meta: AssetMeta;
  setBuffer(buffer: Buffer): void;
  getBuffer(): Promise<Buffer>;
  getMap(): Promise<SourceMap | undefined>;
  addDependency(dependency: DependencyOptions): void;
  addURLDependency(url: string, options?: URLDependencyOptions): void;
  symbols: SymbolMap;
  uniqueKey?: string;
  isSource: boolean;
}

interface AssetEnvironment {
  context: string;
  outputFormat: string;
  engines: { browsers: string };
  shouldOptimize: boolean;
  shouldScopeHoist: boolean;
  sourceMap: boolean;
}

interface AssetMeta {
  type?: string;
  cssModulesCompiled?: boolean;
  hasDependencies?: boolean;
  hasReferences?: boolean;
}

interface DependencyOptions {
  specifier: string;
  specifierType: string;
  loc?: SourceLocation;
  packageConditions?: string[];
  symbols?: Map<string, Symbol>;
  meta?: object;
  env?: object;
}