CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-emotion--cache

Core caching mechanism for Emotion's CSS-in-JS system with customizable style insertion and management

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

index.mddocs/

@emotion/cache

Emotion Cache provides the core caching mechanism for Emotion's CSS-in-JS system, enabling low-level customization of how styles are inserted and managed. It exports a createCache function that creates customizable cache instances with configurable options for security, performance, and DOM manipulation.

Package Information

  • Package Name: @emotion/cache
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @emotion/cache

Core Imports

import createCache from "@emotion/cache";
import type { EmotionCache, StylisElement, StylisPlugin, StylisPluginCallback } from "@emotion/cache";

For CommonJS:

const createCache = require("@emotion/cache");

Architecture

Emotion Cache is built around several key components:

  • Cache Creation: The createCache function serves as the factory for cache instances
  • Style Management: Each cache manages inserted and registered styles separately
  • CSS Processing: Integration with Stylis for CSS preprocessing and plugin support
  • DOM Integration: StyleSheet class handles DOM insertion with performance optimizations
  • Environment Handling: Different behavior for browser vs server-side rendering
  • Security: CSP nonce support and style injection safety

Basic Usage

import createCache from "@emotion/cache";

// Create a basic cache
const myCache = createCache({
  key: "my-app"
});

// Use with CacheProvider in emotion/react
import { CacheProvider } from "@emotion/react";

function App() {
  return (
    <CacheProvider value={myCache}>
      {/* Your emotion-styled components */}
    </CacheProvider>
  );
}

// Advanced configuration with CSP nonce and custom plugins  
const secureCache = createCache({
  key: "secure-app",
  nonce: "random-csp-nonce-value",
  stylisPlugins: [/* custom stylis plugins */],
  container: document.getElementById("styles-container")
});

Capabilities

Cache Creation

Creates customizable cache instances for emotion style management with comprehensive configuration options.

/**
 * Creates a customizable cache instance for emotion style management
 * @param options - Configuration options for the cache
 * @returns EmotionCache instance with configured behavior
 */
function createCache(options: Options): EmotionCache;

interface Options {
  /** Unique identifier for the cache (required) - pattern: [^a-z-] */
  key: string;
  /** CSP nonce for style tags security */
  nonce?: string;
  /** Custom Stylis plugins for CSS preprocessing */
  stylisPlugins?: Array<StylisPlugin>;
  /** DOM node for style tag insertion */
  container?: Node;
  /** Performance optimization flag */
  speedy?: boolean;
  /** @deprecated use insertionPoint instead */
  prepend?: boolean;
  /** DOM element for style insertion point */
  insertionPoint?: HTMLElement;
}

Usage Examples:

// Basic cache for simple applications
const basicCache = createCache({
  key: "emotion"
});

// Cache with CSP security
const secureCache = createCache({
  key: "secure-app",
  nonce: process.env.CSP_NONCE
});

// Cache for iframe usage
const iframeCache = createCache({
  key: "iframe-styles",
  container: iframeDocument.head
});

Cache Management Types

Core types and interfaces for emotion cache functionality.

interface EmotionCache {
  /** Cache identifier */
  key: string;
  /** Stylesheet instance for DOM management */
  sheet: StyleSheet;
  /** CSP nonce for security */
  nonce?: string;
  /** Track inserted styles to prevent duplication */
  inserted: Record<string, string | true | undefined>;
  /** Track registered styles */
  registered: Record<string, string | undefined>;
  /** Compatibility mode flag for server-side rendering */
  compat?: true;
  /** Style insertion function */
  insert: (
    selector: string,
    serialized: SerializedStyles,
    sheet: StyleSheet,
    shouldCache: boolean
  ) => string | void;
}

// Note: SerializedStyles is defined in @emotion/utils, not exported from @emotion/cache
interface SerializedStyles {
  /** Unique name for the style */
  name: string;
  /** CSS styles as string */
  styles: string;
  /** Chain to next serialized style */
  next?: SerializedStyles;
}

// Note: StyleSheet is defined in @emotion/sheet, not exported from @emotion/cache
// This interface is provided for reference only
interface StyleSheet {
  /** Insert CSS rule into the stylesheet */
  insert: (rule: string) => void;
  /** Hydrate stylesheet with existing DOM elements */
  hydrate: (nodes: HTMLElement[]) => void;
  /** Flush all styles from the stylesheet */
  flush: () => void;
}

Stylis Plugin System

Types for extending CSS preprocessing capabilities through custom Stylis plugins.

interface StylisElement {
  /** Element type identifier */
  type: string;
  /** Element value content */
  value: string;
  /** Element properties */
  props: Array<string> | string;
  /** Root element reference */
  root: StylisElement | null;
  /** Parent element reference */
  parent: StylisElement | null;
  /** Child elements */
  children: Array<StylisElement> | string;
  /** Source line number */
  line: number;
  /** Source column number */
  column: number;
  /** Element length */
  length: number;
  /** Return value */
  return: string;
}

/**
 * Stylis plugin function for CSS preprocessing
 * @param element - Current AST element being processed
 * @param index - Index of element in children array
 * @param children - Array of sibling elements
 * @param callback - Callback for recursive processing
 * @returns Processed CSS string or void
 */
type StylisPlugin = (
  element: StylisElement,
  index: number,
  children: Array<StylisElement>,
  callback: StylisPluginCallback
) => string | void;

/**
 * Callback function for Stylis plugin processing
 * @param element - Current AST element being processed
 * @param index - Index of element in children array
 * @param children - Array of sibling elements
 * @param callback - Recursive callback for nested processing
 * @returns Processed CSS string or void
 */
type StylisPluginCallback = (
  element: StylisElement,
  index: number,
  children: Array<StylisElement>,
  callback: StylisPluginCallback
) => string | void;

Usage Examples:

// Custom Stylis plugin for RTL support
const rtlPlugin: StylisPlugin = (element, index, children, callback) => {
  if (element.type === 'decl') {
    // Transform LTR properties to RTL equivalents
    if (element.value.includes('margin-left')) {
      element.value = element.value.replace('margin-left', 'margin-right');
    }
  }
};

// Cache with custom plugin
const rtlCache = createCache({
  key: "rtl-app",
  stylisPlugins: [rtlPlugin]
});

Configuration Details

Security Configuration

CSP nonce support for Content Security Policy compliance:

const secureCache = createCache({
  key: "secure-app",
  nonce: "random-csp-nonce-value" // Applied to all generated style tags
});

DOM Insertion Control

Control where and how styles are inserted into the DOM:

// Insert styles in specific container (useful for iframes)
const containerCache = createCache({
  key: "container-app",
  container: document.getElementById("custom-styles")
});

// Control insertion point for style ordering
const orderedCache = createCache({
  key: "ordered-app", 
  insertionPoint: document.getElementById("before-this-element")
});

Performance Optimization

Speed and caching behavior controls:

const optimizedCache = createCache({
  key: "fast-app",
  speedy: true // Enables performance optimizations
});

Error Handling

The cache creation function validates configuration and throws descriptive errors:

  • Invalid key format: Throws error if key contains invalid characters (must match pattern [^a-z-])
  • Missing key: Throws error in development if no key is provided
  • Unsafe selectors: Logs warnings for potentially unsafe pseudo-selectors in development
  • Import rule placement: Logs errors and removes incorrectly placed @import rules

Environment Compatibility

Emotion Cache handles multiple environments automatically:

  • Browser: Full DOM manipulation with style tag insertion
  • Server-side rendering: Style collection without DOM operations
  • Edge runtime: Optimized builds for edge computing environments
  • Worker environments: Compatible with web workers and service workers

Advanced Use Cases

Multiple Cache Instances

// Separate caches for different style categories
const componentCache = createCache({ key: "comp" });
const utilityCache = createCache({ key: "util" });
const themeCache = createCache({ key: "theme" });

Custom CSS Preprocessing

import { prefixer } from "stylis";

const customCache = createCache({
  key: "custom",
  stylisPlugins: [
    prefixer, // Include prefixer for vendor prefixes
    customRTLPlugin,
    customMinificationPlugin
  ]
});

SSR Hydration

The cache automatically handles server-side rendered styles during hydration, removing SSR styles from the document head and managing the transition to client-side style injection.

docs

index.md

tile.json