PostCSS plugin to rebase, inline, or copy assets from url() declarations with support for multiple transformation modes and advanced filtering options.
npx @tessl/cli install tessl/npm-postcss-url@10.1.0PostCSS 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.
npm install postcss postcss-urlconst postcssUrl = require('postcss-url');ES6/ESM:
import postcssUrl from 'postcss-url';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' });PostCSS URL operates as a PostCSS plugin with a modular architecture:
url() and legacy IE AlphaImageLoader()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');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)';
};
}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;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>);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 functionAdvanced 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;
}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}';
}