or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-csstools--postcss-global-data

PostCSS plugin to define global data that will be injected into PostCSS for use in other plugins.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@csstools/postcss-global-data@3.1.x

To install, run

npx @tessl/cli install tessl/npm-csstools--postcss-global-data@3.1.0

index.mddocs/

PostCSS Global Data

PostCSS Global Data is a PostCSS plugin that enables temporary injection of global CSS data into the PostCSS processing pipeline without affecting the final output. This plugin serves as a data provider for other PostCSS plugins that need access to global CSS rules (such as custom media queries, custom properties, or other CSS variables) to generate appropriate fallbacks or perform transformations.

Package Information

  • Package Name: @csstools/postcss-global-data
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @csstools/postcss-global-data --save-dev (requires postcss as peer dependency)

Core Imports

import postcssGlobalData from '@csstools/postcss-global-data';

For CommonJS:

const postcssGlobalData = require('@csstools/postcss-global-data');

For TypeScript usage with PostCSS types:

import postcssGlobalData, { type pluginOptions } from '@csstools/postcss-global-data';
import type { PluginCreator, Plugin, Root } from 'postcss';

Basic Usage

import postcss from 'postcss';
import postcssGlobalData from '@csstools/postcss-global-data';

postcss([
  postcssGlobalData({
    files: [
      './src/css/variables.css',
      './src/css/media-queries.css',
    ]
  })
]).process(YOUR_CSS /*, processOptions */);

Capabilities

Plugin Creation

Creates a PostCSS plugin instance that injects CSS from specified files during processing.

/**
 * Creates a PostCSS plugin that injects global CSS data
 * @param opts - Configuration options for the plugin
 * @returns Plugin creator function or configuration object with plugins array
 */
function postcssGlobalData(opts?: pluginOptions): PluginCreator<pluginOptions> | PluginConfigWithLateRemover;

// When lateRemover: false (default), returns a standard plugin creator
interface PluginCreator<T> {
  postcssPlugin: string;
  prepare(): Plugin;
}

// When lateRemover: true, returns object with plugins array
interface PluginConfigWithLateRemover {
  postcssPlugin: string;
  plugins: [PluginCreator<pluginOptions>, LateRemoverPlugin];
}

interface LateRemoverPlugin {
  postcssPlugin: string;
  OnceExit(root: Root): void;
}

// Referenced PostCSS types
interface Plugin {
  postcssPlugin: string;
  Once?(root: Root, helpers: Helpers): void;
  OnceExit?(root: Root): void;
}

interface Root {
  // PostCSS AST root node
}

interface Helpers {
  result: Result;
  postcss: typeof postcss;
}

interface Result {
  // PostCSS result object containing messages and other metadata
  messages: Array<{ type: string; plugin: string; file?: string; parent?: string }>;
}

Configuration Options:

export type pluginOptions = {
  /** List of files to be used as context */
  files?: Array<string>;
  /** Remove nodes in a separate plugin object, this object can be added later in your list of plugins */
  lateRemover?: boolean;
  /** Add global CSS to the start of files, defaults to `false` */
  prepend?: boolean;
};

Standard Mode (lateRemover: false)

Returns a single PostCSS plugin that injects CSS during the Once phase and removes it during the OnceExit phase.

const plugin = postcssGlobalData({
  files: ['./global.css'],
  prepend: false
});

postcss([plugin]).process(css);

Late Remover Mode (lateRemover: true)

Returns an object with a plugins array containing two separate plugins, allowing other plugins to run between injection and removal.

const globalDataConfig = postcssGlobalData({ 
  files: ['./global.css'],
  lateRemover: true
});

const [globalData, globalDataLateRemover] = globalDataConfig.plugins;

postcss([
  globalData,
  // other plugins can access the injected data here
  someOtherPlugin(),
  globalDataLateRemover
]).process(css);

File Path Resolution

The plugin supports multiple file path formats for flexible module resolution:

  • Absolute paths: Resolved using path.resolve(filePath)
  • Node modules with node_modules:// prefix: Uses require.resolve() to locate package files
  • Node modules with node_modules: prefix: Alternative syntax for package resolution
postcssGlobalData({
  files: [
    './local-file.css',                    // Relative path
    '/absolute/path/to/file.css',          // Absolute path
    'node_modules://package-name/file.css', // Package file with :// syntax
    'node_modules:package-name/file.css'   // Package file with : syntax
  ]
});

Configuration Options

files

Specifies which CSS files to inject into the PostCSS processing pipeline.

files?: Array<string>
  • Default: [] (empty array)
  • Supports absolute paths, relative paths, and node_modules: prefixed paths
  • Throws descriptive errors for unreadable or missing files

lateRemover

Controls the plugin execution strategy. When true, returns separate injection and removal plugins for advanced plugin ordering.

lateRemover?: boolean
  • Default: false
  • When false: Returns single plugin object with built-in cleanup
  • When true: Returns object with plugins array containing two separate plugins

prepend

Determines whether injected CSS is added before or after existing content. When true, CSS is prepended; when false, it's appended.

prepend?: boolean
  • Default: false
  • When false: CSS is appended after existing content
  • When true: CSS is prepended before existing content

Warning: Prepending styles before @import statements will create invalid stylesheets.

Plugin Behavior

CSS Injection Process

  1. During the Once phase, the plugin reads specified CSS files
  2. File contents are parsed into PostCSS AST nodes
  3. Nodes are injected into the current stylesheet (appended or prepended based on configuration)
  4. A tracking mechanism records which nodes were injected

CSS Removal Process

  1. During the OnceExit phase, injected nodes are removed from the stylesheet
  2. File tracking sets are cleared to prevent memory leaks
  3. Final output contains no trace of the injected CSS

Dependency Tracking

The plugin automatically registers file dependencies with PostCSS, enabling proper watch mode functionality and build system integration.

Error Handling

/**
 * The plugin throws Error instances in these cases:
 * @throws {Error} When files cannot be read or resolved
 * @throws {Error} When file paths are malformed
 * @throws {Error} When module resolution fails for node_modules: paths
 */

Error scenarios:

  • File Read Errors: Failed to read ${filePath} with error ${errorMessage}
  • Module Resolution Errors: When node_modules: or node_modules:// prefixed paths cannot be resolved
  • Path Resolution Errors: When relative or absolute paths point to non-existent files

PostCSS Integration

Dependency Tracking

The plugin automatically registers file dependencies with PostCSS for proper build system integration:

// Automatically adds dependency messages to PostCSS result
interface DependencyMessage {
  type: 'dependency';
  plugin: 'postcss-global-data';
  file: string;        // Resolved file path
  parent?: string;     // Parent file path
}

This enables:

  • Watch mode functionality in build systems
  • Proper cache invalidation
  • Dependency graph construction

Use Cases

CSS Modules with PostCSS Custom Media

postcss([
  postcssGlobalData({
    files: ['./media-queries.css']
  }),
  postcssCustomMedia() // Can now generate fallbacks using global media queries
])

Global Variable Access

postcss([
  postcssGlobalData({
    files: [
      './css-variables.css',
      './custom-properties.css'
    ]
  }),
  postcssCustomProperties() // Can access global custom properties
])

Build System Integration

postcss([
  postcssGlobalData({
    files: [
      'node_modules:open-props/props.css', // External package
      './src/design-tokens.css'            // Local tokens
    ],
    prepend: true
  })
])

Advanced Type Information

Exported Types

// Main plugin configuration type (exported from the package)
export type pluginOptions = {
  files?: Array<string>;
  lateRemover?: boolean;
  prepend?: boolean;
};

// Return types based on configuration
type PostCSSGlobalDataReturn<T extends pluginOptions> = 
  T["lateRemover"] extends true 
    ? PluginConfigWithLateRemover
    : PluginCreator<pluginOptions>;

// Standard mode return type (lateRemover: false)
interface StandardModeReturn extends PluginCreator<pluginOptions> {
  postcssPlugin: "postcss-global-data";
  prepare(): Plugin;
}

// Late remover mode return type (lateRemover: true) 
interface LateRemoverModeReturn {
  postcssPlugin: "postcss-global-data";
  plugins: [PluginCreator<pluginOptions>, LateRemoverPlugin];
}

interface LateRemoverPlugin {
  postcssPlugin: "postcss-global-data/late-remover";
  OnceExit(root: Root): void;
}

PostCSS Plugin Lifecycle

// Plugin hooks used internally
interface PluginHooks {
  Once(root: Root, postcssHelpers: Helpers): void;  // CSS injection phase
  OnceExit(): void;                                 // CSS removal phase
}

// PostCSS helpers provided to plugins
interface Helpers {
  result: Result;
  postcss: typeof postcss;
}