or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

asset-filtering.mdencoding-optimization.mdindex.mdplugin-options.mdprocessing-modes.md
tile.json

tessl/npm-postcss-url

PostCSS plugin to rebase, inline, or copy assets from url() declarations with support for multiple transformation modes and advanced filtering options.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/postcss-url@10.1.x

To install, run

npx @tessl/cli install tessl/npm-postcss-url@10.1.0

index.mddocs/

PostCSS URL

PostCSS URL is a PostCSS plugin that transforms CSS url() declarations and Microsoft AlphaImageLoader patterns by rebasing relative paths, inlining assets as data URIs, or copying assets to specified locations. It provides flexible asset processing with advanced filtering, custom transformations, and multiple processing modes to optimize CSS build pipelines.

Package Information

  • Package Name: postcss-url
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install postcss postcss-url

Core Imports

const postcssUrl = require('postcss-url');

ES6/ESM:

import postcssUrl from 'postcss-url';

Basic Usage

const postcss = require('postcss');
const postcssUrl = require('postcss-url');

// Basic rebase mode (default)
const result = await postcss()
  .use(postcssUrl({
    url: 'rebase'
  }))
  .process(css, {
    from: 'src/styles/main.css',
    to: 'dist/styles/main.css'
  });

// Inline assets as data URIs
const inlineResult = await postcss()
  .use(postcssUrl({
    url: 'inline',
    maxSize: 10 // 10KB limit
  }))
  .process(css, { from: 'src/main.css', to: 'dist/main.css' });

// Copy assets with hash names
const copyResult = await postcss()
  .use(postcssUrl({
    url: 'copy',
    assetsPath: 'assets',
    useHash: true
  }))
  .process(css, { from: 'src/main.css', to: 'dist/main.css' });

Architecture

PostCSS URL operates as a PostCSS plugin with a modular architecture:

  • Plugin Core: Main plugin function that integrates with PostCSS processing pipeline
  • Declaration Processor: Scans CSS declarations for URL patterns and coordinates transformations
  • URL Pattern Matching: Supports multiple URL pattern types including url() and legacy IE AlphaImageLoader()
  • Processing Modes: Four distinct transformation strategies (rebase, inline, copy, custom)
  • Asset Resolution: Path resolution system supporting base paths and file discovery
  • Filtering System: Pattern-based asset filtering using minimatch, regex, or custom functions
  • Options Matching: Multi-option processing with priority and fallback handling

Supported URL Patterns

The plugin automatically detects and processes these CSS patterns:

/* Standard CSS url() declarations */
background: url('path/to/image.png');
background-image: url("../assets/hero.jpg");

/* Microsoft AlphaImageLoader (IE compatibility) */
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='image.png');

Built-in URL Validation

The plugin automatically ignores certain URL types that don't require processing:

interface BuiltInValidation {
  /** URLs automatically ignored by the plugin */
  ignored: {
    /** Data URIs */
    dataUris: 'data:*';
    /** Absolute URLs with protocol */
    protocols: 'http://, https://, ftp://, etc.';
    /** Protocol-relative URLs */
    protocolRelative: '//*';
    /** Hash-only URLs */
    hashOnly: '#*';
    /** URL-encoded hash URLs */
    encodedHash: '%23*';
    /** Absolute paths without basePath option */
    absolutePaths: '/* (when basePath not specified)';
    /** Tilde paths without basePath option */
    tildePaths: '~* (when basePath not specified)';
  };
}

Capabilities

Main Plugin Function

Core PostCSS plugin factory that creates configured plugin instances for CSS processing.

/**
 * Creates a PostCSS plugin instance with specified options
 * @param {PostcssUrlOptions|PostcssUrlOptions[]} options - Plugin configuration
 * @returns {PostcssPlugin} PostCSS plugin object
 */
function postcssUrl(options?: PostcssUrlOptions | PostcssUrlOptions[]): PostcssPlugin;

interface PostcssPlugin {
  postcssPlugin: 'postcss-url';
  Once(root: any, helpers: { result: any }): Promise<void>;
}
// The plugin also has a postcss property set to true
postcssUrl.postcss = true;

Plugin Configuration

Processing Modes

Four built-in transformation modes for handling CSS url() declarations with different optimization strategies.

type ProcessingMode = 'rebase' | 'inline' | 'copy' | ((asset: Asset, dir: Dir, options: any) => string | Promise<string>);

Processing Modes

Asset Filtering

Pattern-based filtering system for selectively processing assets based on paths, file types, or custom criteria.

type FilterPattern = 
  | string          // minimatch pattern like '**/*.png'
  | RegExp          // regular expression
  | ((asset: Asset) => boolean);  // custom filter function

Asset Filtering

Encoding and Optimization

Advanced encoding capabilities with automatic MIME type detection, SVG optimization, and multiple encoding strategies.

type EncodeType = 'base64' | 'encodeURI' | 'encodeURIComponent';

interface EncodingFeatures {
  /** Automatic MIME type detection using mime package */
  mimeDetection: boolean;
  /** SVG optimization for better compression */
  svgOptimization: boolean;
  /** URI fragment handling for SVG files */
  fragmentHandling: boolean;
  /** Automatic quote management for encoded URIs */
  quoteHandling: boolean;
}

Encoding and Optimization

Types

interface PostcssUrlOptions {
  /** Processing mode or custom transform function */
  url?: ProcessingMode;
  /** Filter pattern for selective asset processing */
  filter?: FilterPattern;
  /** Directory to copy assets (relative to 'to' option or absolute) */
  assetsPath?: string;
  /** Base path(s) to search for assets */
  basePath?: string | string[];
  /** Maximum file size in KB for inline mode */
  maxSize?: number;
  /** Fallback mode when file exceeds maxSize */
  fallback?: ProcessingMode;
  /** Use content hash for asset filenames */
  useHash?: boolean;
  /** Hash generation options */
  hashOptions?: HashOptions;
  /** Encoding type for inline mode */
  encodeType?: 'base64' | 'encodeURI' | 'encodeURIComponent';
  /** Include URI fragment in data URI */
  includeUriFragment?: boolean;
  /** Suppress SVG fragment warnings */
  ignoreFragmentWarning?: boolean;
  /** Optimize SVG encoding for better compression */
  optimizeSvgEncode?: boolean;
  /** Allow processing with subsequent options (custom mode) */
  multi?: boolean;
}

interface HashOptions {
  /** Hash algorithm or custom function */
  method?: 'xxhash32' | 'xxhash64' | string | ((content: Buffer) => string);
  /** Number of characters to keep from hash */
  shrink?: number;
  /** Prepend original filename to hash */
  append?: boolean;
}

interface Asset {
  /** Original URL from CSS */
  url: string;
  /** Original URL (preserved for reference) */
  originUrl: string;
  /** URL pathname without search/hash */
  pathname: string;
  /** Absolute path to asset file */
  absolutePath: string;
  /** Relative path from source */
  relativePath: string;
  /** Query string from URL */
  search: string;
  /** Hash fragment from URL */
  hash: string;
}

interface Dir {
  /** Source directory (from PostCSS 'from' option) */
  from: string;
  /** Target directory (from PostCSS 'to' option) */
  to: string;
  /** CSS file directory */
  file: string;
}

interface File {
  /** Absolute path to the asset file */
  path: string;
  /** File contents as Buffer */
  contents: Buffer;
  /** MIME type detected from file extension */
  mimeType: string;
}

interface ValidationErrors {
  /** Unknown processing mode error */
  unknownMode: 'Unknown mode for postcss-url: ${mode}';
  /** Missing required PostCSS 'to' option for copy mode */
  missingToOption: 'Option `to` of postcss is required, ignoring';
  /** Asset file not found */
  fileNotFound: 'Can\'t read file \'${paths}\', ignoring';
  /** Missing MIME type detection */
  missingMimeType: 'Unable to find asset mime-type for ${filePath}';
  /** SVG fragment warning */
  svgFragment: 'Image type is svg and link contains #. Postcss-url cant handle svg fragments. SVG file fully inlined. ${filePath}';
}