CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-style-loader

Webpack loader that dynamically injects CSS into the DOM at runtime with multiple injection strategies and CSS modules support

Pending
Overview
Eval results
Files

runtime-api.mddocs/

Runtime API

Low-level runtime functions for DOM manipulation, style injection, and element management.

Capabilities

Style Injection Functions

Core functions that handle the injection of CSS content into the DOM via different strategies.

injectStylesIntoStyleTag

Main style injection manager for <style> elements with full feature support.

/**
 * Injects CSS modules into <style> elements
 * @param list - Array of CSS modules to inject
 * @param options - Runtime configuration options
 * @returns Update function for modifying injected styles
 */
function injectStylesIntoStyleTag(
  list: CSSModule[], 
  options: RuntimeOptions
): UpdateFunction;

type UpdateFunction = (newList?: CSSModule[] | null) => void;

injectStylesIntoLinkTag

Link tag injection manager for <link rel="stylesheet"> elements.

/**
 * Injects CSS via <link> elements
 * @param url - CSS file URL to load
 * @param options - Runtime configuration options  
 * @returns Update function for changing URL or removing link
 */
function injectStylesIntoLinkTag(
  url: string,
  options: RuntimeOptions
): UpdateFunction;

type UpdateFunction = (newUrl?: string | null) => void;

DOM API Functions

Low-level DOM manipulation functions for creating and managing style elements.

styleDomAPI

DOM API for individual style elements with full CSS feature support including source maps, media queries, CSS cascade layers, and @supports rules.

/**
 * Creates DOM API for individual style elements
 * @param options - Runtime options including insertion and attribute functions
 * @returns Object with update and remove methods
 */
function styleDomAPI(options: RuntimeOptions): DOMAPIResult;

interface DOMAPIResult {
  /**
   * Updates the style element with new CSS content
   * @param obj - CSS module with content, media, supports, layer
   */
  update(obj: CSSModule): void;
  
  /**
   * Removes the style element from DOM
   */
  remove(): void;
}

singletonStyleDomAPI

DOM API for singleton style elements that share a single <style> tag across multiple CSS modules.

/**
 * Creates DOM API for singleton style management
 * @param options - Runtime options for shared style element
 * @returns Object with update and remove methods
 */
function singletonStyleDomAPI(options: RuntimeOptions): DOMAPIResult;

// Same interface as styleDomAPI but manages shared element internally
interface DOMAPIResult {
  update(obj: CSSModule): void;
  remove(): void;
}

Element Creation and Management

Functions for creating and configuring DOM elements used by the style injection system.

insertStyleElement

Factory function for creating <style> elements with proper configuration.

/**
 * Creates a new style element with configured attributes and insertion
 * @param options - Configuration for element creation
 * @returns Created HTML style element
 */
function insertStyleElement(options: StyleElementOptions): HTMLStyleElement;

interface StyleElementOptions {
  setAttributes: (element: HTMLStyleElement, attributes?: object) => void;
  attributes?: Record<string, string>;
  insert: (element: HTMLStyleElement, options?: object) => void;
  options?: object;
}

insertBySelector

Inserts style elements into the DOM using CSS selectors for target location with iframe support.

/**
 * Inserts element at location specified by CSS selector
 * Handles iframe content document access with memoization
 * @param insert - CSS selector string for target location
 * @param style - Style element to insert
 */
function insertBySelector(insert: string, style: HTMLElement): void;

Attribute Management

Functions for setting HTML attributes on style and link elements.

setAttributesWithAttributes

Sets custom attributes on elements with automatic webpack nonce handling.

/**
 * Sets custom attributes with automatic webpack nonce
 * @param styleElement - Target HTML element
 * @param attributes - Object containing attribute key-value pairs
 */
function setAttributesWithAttributes(
  styleElement: HTMLElement, 
  attributes: Record<string, string>
): void;

setAttributesWithAttributesAndNonce

Sets custom attributes on elements without automatic nonce handling.

/**
 * Sets custom attributes without automatic nonce handling
 * @param styleElement - Target HTML element  
 * @param attributes - Object containing attribute key-value pairs
 */
function setAttributesWithAttributesAndNonce(
  styleElement: HTMLElement,
  attributes: Record<string, string>
): void;

setAttributesWithoutAttributes

Minimal attribute setter that only handles webpack nonce.

/**
 * Sets only webpack nonce attribute
 * @param element - Target HTML element
 */
function setAttributesWithoutAttributes(element: HTMLElement): void;

CSS Content Processing

Functions for processing and transforming CSS content before DOM insertion.

styleTagTransform

Default CSS content insertion function with cross-browser compatibility.

/**
 * Inserts CSS content into style elements with IE compatibility
 * @param css - CSS content string
 * @param styleElement - Target style element
 */
function styleTagTransform(css: string, styleElement: HTMLStyleElement): void;

Utility Functions

Helper functions for browser detection and data comparison.

isOldIE

Detects Internet Explorer versions 6-9 with memoization using document.all && !window.atob feature detection.

/**
 * Detects IE6-9 browsers using feature detection
 * Uses memoization for performance - checks document.all exists but window.atob doesn't
 * @returns True if browser is IE6-9, false otherwise
 */
function isOldIE(): boolean;

isEqualLocals

Deep equality comparison for CSS module locals, used in Hot Module Replacement.

/**
 * Compares CSS module locals for equality  
 * @param a - First locals object
 * @param b - Second locals object
 * @param isNamedExport - Whether to skip 'default' property comparison
 * @returns True if locals are equal, false otherwise
 */
function isEqualLocals(
  a: Record<string, any>, 
  b: Record<string, any>, 
  isNamedExport: boolean
): boolean;

Runtime Configuration Types

Core types used throughout the runtime API system.

/**
 * CSS module format used throughout runtime system
 * Array format: [id, css, media?, sourceMap?, supports?, layer?]
 */
type CSSModule = [
  string,        // Module identifier
  string,        // CSS content  
  string?,       // Media query (e.g., "screen and (max-width: 768px)")
  string?,       // Source map (base64 encoded)
  string?,       // Supports rule (e.g., "display: grid")
  string?        // CSS cascade layer name (e.g., "utilities", "components")
];

/**
 * Runtime options passed to injection and DOM API functions
 */
interface RuntimeOptions {
  /** Custom HTML attributes for elements */
  attributes?: Record<string, string>;
  
  /** DOM insertion function */
  insert?: (element: HTMLElement) => void;
  
  /** DOM API implementation function */
  domAPI?: DOMAPIFunction;
  
  /** Style element creation function */
  insertStyleElement?: (options: StyleElementOptions) => HTMLStyleElement;
  
  /** Attribute setting function */
  setAttributes?: (element: HTMLElement, attributes?: object) => void;
  
  /** CSS transformation function */
  styleTagTransform?: (css: string, element: HTMLStyleElement) => void;
  
  /** Base number for module IDs */
  base?: number;
}

/**
 * DOM API function signature
 */
interface DOMAPIFunction {
  (options: RuntimeOptions): {
    update(obj: CSSModule): void;
    remove(): void;
  };
}

Advanced Usage Examples

Custom DOM API Implementation

// custom-dom-api.js
function customDomAPI(options) {
  let styleElement;
  
  return {
    update(obj) {
      if (!styleElement) {
        styleElement = options.insertStyleElement({
          setAttributes: options.setAttributes,
          attributes: options.attributes,
          insert: options.insert,
          options: options.options
        });
      }
      
      // Custom CSS processing
      const processedCSS = obj[1].replace(/\/\*.*?\*\//g, ''); // Remove comments
      options.styleTagTransform(processedCSS, styleElement);
    },
    
    remove() {
      if (styleElement && styleElement.parentNode) {
        styleElement.parentNode.removeChild(styleElement);
        styleElement = null;
      }
    }
  };
}

module.exports = customDomAPI;

Custom Insertion Function

// custom-insert.js
function customInsert(element) {
  // Insert at specific location in shadow DOM
  const shadowHost = document.getElementById('shadow-host');
  if (shadowHost && shadowHost.shadowRoot) {
    shadowHost.shadowRoot.appendChild(element);
  } else {
    // Fallback to document head
    document.head.appendChild(element);
  }
}

module.exports = customInsert;

Runtime Options Configuration

// Advanced runtime configuration example
const runtimeOptions = {
  attributes: {
    'data-component': 'MyComponent',
    'data-version': '1.0.0'
  },
  
  insert: function(element) {
    // Custom insertion logic
    const target = document.querySelector('#style-container') || document.head;
    target.appendChild(element);
  },
  
  domAPI: customDomAPI,
  
  setAttributes: function(element, attributes) {
    // Custom attribute setting
    if (attributes) {
      Object.keys(attributes).forEach(key => {
        element.setAttribute(key, attributes[key]);
      });
    }
    
    // Add CSP nonce if available
    if (typeof __webpack_nonce__ !== 'undefined') {
      element.setAttribute('nonce', __webpack_nonce__);
    }
  },
  
  styleTagTransform: function(css, styleElement) {
    // Custom CSS transformation
    const minifiedCSS = css.replace(/\s+/g, ' ').trim();
    
    if (styleElement.styleSheet) {
      styleElement.styleSheet.cssText = minifiedCSS;
    } else {
      styleElement.textContent = minifiedCSS;
    }
  }
};

Install with Tessl CLI

npx tessl i tessl/npm-style-loader

docs

css-modules.md

index.md

injection-types.md

loader-configuration.md

runtime-api.md

tile.json