0
# PostCSS URL
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: postcss-url
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install postcss postcss-url`
10
11
## Core Imports
12
13
```javascript
14
const postcssUrl = require('postcss-url');
15
```
16
17
ES6/ESM:
18
19
```javascript
20
import postcssUrl from 'postcss-url';
21
```
22
23
## Basic Usage
24
25
```javascript
26
const postcss = require('postcss');
27
const postcssUrl = require('postcss-url');
28
29
// Basic rebase mode (default)
30
const result = await postcss()
31
.use(postcssUrl({
32
url: 'rebase'
33
}))
34
.process(css, {
35
from: 'src/styles/main.css',
36
to: 'dist/styles/main.css'
37
});
38
39
// Inline assets as data URIs
40
const inlineResult = await postcss()
41
.use(postcssUrl({
42
url: 'inline',
43
maxSize: 10 // 10KB limit
44
}))
45
.process(css, { from: 'src/main.css', to: 'dist/main.css' });
46
47
// Copy assets with hash names
48
const copyResult = await postcss()
49
.use(postcssUrl({
50
url: 'copy',
51
assetsPath: 'assets',
52
useHash: true
53
}))
54
.process(css, { from: 'src/main.css', to: 'dist/main.css' });
55
```
56
57
## Architecture
58
59
PostCSS URL operates as a PostCSS plugin with a modular architecture:
60
61
- **Plugin Core**: Main plugin function that integrates with PostCSS processing pipeline
62
- **Declaration Processor**: Scans CSS declarations for URL patterns and coordinates transformations
63
- **URL Pattern Matching**: Supports multiple URL pattern types including `url()` and legacy IE `AlphaImageLoader()`
64
- **Processing Modes**: Four distinct transformation strategies (rebase, inline, copy, custom)
65
- **Asset Resolution**: Path resolution system supporting base paths and file discovery
66
- **Filtering System**: Pattern-based asset filtering using minimatch, regex, or custom functions
67
- **Options Matching**: Multi-option processing with priority and fallback handling
68
69
### Supported URL Patterns
70
71
The plugin automatically detects and processes these CSS patterns:
72
73
```css
74
/* Standard CSS url() declarations */
75
background: url('path/to/image.png');
76
background-image: url("../assets/hero.jpg");
77
78
/* Microsoft AlphaImageLoader (IE compatibility) */
79
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='image.png');
80
```
81
82
### Built-in URL Validation
83
84
The plugin automatically ignores certain URL types that don't require processing:
85
86
```javascript { .api }
87
interface BuiltInValidation {
88
/** URLs automatically ignored by the plugin */
89
ignored: {
90
/** Data URIs */
91
dataUris: 'data:*';
92
/** Absolute URLs with protocol */
93
protocols: 'http://, https://, ftp://, etc.';
94
/** Protocol-relative URLs */
95
protocolRelative: '//*';
96
/** Hash-only URLs */
97
hashOnly: '#*';
98
/** URL-encoded hash URLs */
99
encodedHash: '%23*';
100
/** Absolute paths without basePath option */
101
absolutePaths: '/* (when basePath not specified)';
102
/** Tilde paths without basePath option */
103
tildePaths: '~* (when basePath not specified)';
104
};
105
}
106
```
107
108
## Capabilities
109
110
### Main Plugin Function
111
112
Core PostCSS plugin factory that creates configured plugin instances for CSS processing.
113
114
```javascript { .api }
115
/**
116
* Creates a PostCSS plugin instance with specified options
117
* @param {PostcssUrlOptions|PostcssUrlOptions[]} options - Plugin configuration
118
* @returns {PostcssPlugin} PostCSS plugin object
119
*/
120
function postcssUrl(options?: PostcssUrlOptions | PostcssUrlOptions[]): PostcssPlugin;
121
122
interface PostcssPlugin {
123
postcssPlugin: 'postcss-url';
124
Once(root: any, helpers: { result: any }): Promise<void>;
125
}
126
// The plugin also has a postcss property set to true
127
postcssUrl.postcss = true;
128
```
129
130
[Plugin Configuration](./plugin-options.md)
131
132
### Processing Modes
133
134
Four built-in transformation modes for handling CSS url() declarations with different optimization strategies.
135
136
```javascript { .api }
137
type ProcessingMode = 'rebase' | 'inline' | 'copy' | ((asset: Asset, dir: Dir, options: any) => string | Promise<string>);
138
```
139
140
[Processing Modes](./processing-modes.md)
141
142
### Asset Filtering
143
144
Pattern-based filtering system for selectively processing assets based on paths, file types, or custom criteria.
145
146
```javascript { .api }
147
type FilterPattern =
148
| string // minimatch pattern like '**/*.png'
149
| RegExp // regular expression
150
| ((asset: Asset) => boolean); // custom filter function
151
```
152
153
[Asset Filtering](./asset-filtering.md)
154
155
### Encoding and Optimization
156
157
Advanced encoding capabilities with automatic MIME type detection, SVG optimization, and multiple encoding strategies.
158
159
```javascript { .api }
160
type EncodeType = 'base64' | 'encodeURI' | 'encodeURIComponent';
161
162
interface EncodingFeatures {
163
/** Automatic MIME type detection using mime package */
164
mimeDetection: boolean;
165
/** SVG optimization for better compression */
166
svgOptimization: boolean;
167
/** URI fragment handling for SVG files */
168
fragmentHandling: boolean;
169
/** Automatic quote management for encoded URIs */
170
quoteHandling: boolean;
171
}
172
```
173
174
[Encoding and Optimization](./encoding-optimization.md)
175
176
## Types
177
178
```javascript { .api }
179
interface PostcssUrlOptions {
180
/** Processing mode or custom transform function */
181
url?: ProcessingMode;
182
/** Filter pattern for selective asset processing */
183
filter?: FilterPattern;
184
/** Directory to copy assets (relative to 'to' option or absolute) */
185
assetsPath?: string;
186
/** Base path(s) to search for assets */
187
basePath?: string | string[];
188
/** Maximum file size in KB for inline mode */
189
maxSize?: number;
190
/** Fallback mode when file exceeds maxSize */
191
fallback?: ProcessingMode;
192
/** Use content hash for asset filenames */
193
useHash?: boolean;
194
/** Hash generation options */
195
hashOptions?: HashOptions;
196
/** Encoding type for inline mode */
197
encodeType?: 'base64' | 'encodeURI' | 'encodeURIComponent';
198
/** Include URI fragment in data URI */
199
includeUriFragment?: boolean;
200
/** Suppress SVG fragment warnings */
201
ignoreFragmentWarning?: boolean;
202
/** Optimize SVG encoding for better compression */
203
optimizeSvgEncode?: boolean;
204
/** Allow processing with subsequent options (custom mode) */
205
multi?: boolean;
206
}
207
208
interface HashOptions {
209
/** Hash algorithm or custom function */
210
method?: 'xxhash32' | 'xxhash64' | string | ((content: Buffer) => string);
211
/** Number of characters to keep from hash */
212
shrink?: number;
213
/** Prepend original filename to hash */
214
append?: boolean;
215
}
216
217
interface Asset {
218
/** Original URL from CSS */
219
url: string;
220
/** Original URL (preserved for reference) */
221
originUrl: string;
222
/** URL pathname without search/hash */
223
pathname: string;
224
/** Absolute path to asset file */
225
absolutePath: string;
226
/** Relative path from source */
227
relativePath: string;
228
/** Query string from URL */
229
search: string;
230
/** Hash fragment from URL */
231
hash: string;
232
}
233
234
interface Dir {
235
/** Source directory (from PostCSS 'from' option) */
236
from: string;
237
/** Target directory (from PostCSS 'to' option) */
238
to: string;
239
/** CSS file directory */
240
file: string;
241
}
242
243
interface File {
244
/** Absolute path to the asset file */
245
path: string;
246
/** File contents as Buffer */
247
contents: Buffer;
248
/** MIME type detected from file extension */
249
mimeType: string;
250
}
251
252
interface ValidationErrors {
253
/** Unknown processing mode error */
254
unknownMode: 'Unknown mode for postcss-url: ${mode}';
255
/** Missing required PostCSS 'to' option for copy mode */
256
missingToOption: 'Option `to` of postcss is required, ignoring';
257
/** Asset file not found */
258
fileNotFound: 'Can\'t read file \'${paths}\', ignoring';
259
/** Missing MIME type detection */
260
missingMimeType: 'Unable to find asset mime-type for ${filePath}';
261
/** SVG fragment warning */
262
svgFragment: 'Image type is svg and link contains #. Postcss-url cant handle svg fragments. SVG file fully inlined. ${filePath}';
263
}
264
```