0
# Processing Modes
1
2
PostCSS URL provides four distinct processing modes for transforming CSS url() declarations: rebase, inline, copy, and custom. Each mode optimizes assets differently based on deployment needs and performance requirements.
3
4
## Capabilities
5
6
### Rebase Mode
7
8
Adjusts relative URLs based on the difference between source and target file locations. This is the default mode when no options are specified.
9
10
```javascript { .api }
11
/**
12
* Rebase mode configuration
13
* @param {RebaseOptions} options - Rebase-specific options
14
*/
15
interface RebaseOptions {
16
url: 'rebase';
17
/** Optional assets path for URL adjustment */
18
assetsPath?: string;
19
}
20
```
21
22
**Usage Example:**
23
24
```javascript
25
const postcss = require('postcss');
26
const postcssUrl = require('postcss-url');
27
28
// Rebase URLs based on file locations
29
const result = await postcss()
30
.use(postcssUrl({
31
url: 'rebase'
32
}))
33
.process(css, {
34
from: 'src/styles/components/button.css',
35
to: 'dist/styles/main.css'
36
});
37
38
// Before: background: url('../images/icon.png');
39
// After: background: url('../src/styles/images/icon.png');
40
```
41
42
**With Assets Path:**
43
44
```javascript
45
// Rebase with custom assets directory
46
const result = await postcss()
47
.use(postcssUrl({
48
url: 'rebase',
49
assetsPath: 'static/assets'
50
}))
51
.process(css, { from: 'src/main.css', to: 'dist/main.css' });
52
```
53
54
### Inline Mode
55
56
Converts asset files to data URIs (base64 or URI-encoded) and embeds them directly in the CSS. Ideal for small assets to reduce HTTP requests.
57
58
```javascript { .api }
59
/**
60
* Inline mode configuration
61
* @param {InlineOptions} options - Inline-specific options
62
*/
63
interface InlineOptions {
64
url: 'inline';
65
/** Base path(s) to search for assets */
66
basePath?: string | string[];
67
/** Encoding type for data URI */
68
encodeType?: 'base64' | 'encodeURI' | 'encodeURIComponent';
69
/** Maximum file size in KB to inline */
70
maxSize?: number;
71
/** Fallback mode when file exceeds maxSize */
72
fallback?: 'copy' | 'rebase' | ((asset: Asset, dir: Dir, options: any) => string);
73
/** Include URI fragment in data URI */
74
includeUriFragment?: boolean;
75
/** Suppress SVG fragment warnings */
76
ignoreFragmentWarning?: boolean;
77
/** Optimize SVG encoding for better compression */
78
optimizeSvgEncode?: boolean;
79
}
80
```
81
82
**Basic Inline Example:**
83
84
```javascript
85
// Inline all assets as data URIs
86
const result = await postcss()
87
.use(postcssUrl({
88
url: 'inline'
89
}))
90
.process(css, { from: 'src/main.css', to: 'dist/main.css' });
91
92
// Before: background: url('./icon.png');
93
// After: background: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...');
94
```
95
96
**Advanced Inline Example:**
97
98
```javascript
99
// Inline with size limits and fallback
100
const result = await postcss()
101
.use(postcssUrl({
102
url: 'inline',
103
maxSize: 10, // 10KB limit
104
fallback: 'copy', // Copy large files
105
encodeType: 'base64', // Use base64 encoding
106
basePath: ['src/assets', 'node_modules/icons']
107
}))
108
.process(css, { from: 'src/main.css', to: 'dist/main.css' });
109
```
110
111
**SVG Optimization Example:**
112
113
```javascript
114
// Optimized SVG inlining
115
const result = await postcss()
116
.use(postcssUrl({
117
url: 'inline',
118
encodeType: 'encodeURIComponent',
119
optimizeSvgEncode: true, // Optimize SVG encoding
120
ignoreFragmentWarning: true // Suppress fragment warnings
121
}))
122
.process(css, { from: 'src/main.css', to: 'dist/main.css' });
123
124
// SVG files are URI-encoded with optimizations
125
// Before: background: url('./icon.svg');
126
// After: background: url('data:image/svg+xml,%3Csvg xmlns%3D...');
127
```
128
129
**MIME Type Detection:**
130
131
The inline mode automatically detects file types using the `mime` package and applies appropriate encoding:
132
133
```javascript
134
// Automatic MIME type detection and encoding selection
135
const result = await postcss()
136
.use(postcssUrl({
137
url: 'inline'
138
// SVG files automatically use 'encodeURIComponent'
139
// Other files automatically use 'base64'
140
}))
141
.process(css, { from: 'src/main.css', to: 'dist/main.css' });
142
143
// PNG: data:image/png;base64,iVBORw0KGgoAAAANSUh...
144
// SVG: data:image/svg+xml,%3Csvg xmlns%3D%22http...
145
// JPEG: data:image/jpeg;base64,/9j/4AAQSkZJRgABAQ...
146
```
147
148
### Copy Mode
149
150
Copies asset files to a specified directory and updates URLs to point to the copied files. Supports hash-based renaming for cache busting.
151
152
```javascript { .api }
153
/**
154
* Copy mode configuration
155
* @param {CopyOptions} options - Copy-specific options
156
*/
157
interface CopyOptions {
158
url: 'copy';
159
/** Directory to copy assets (relative to 'to' option or absolute) */
160
assetsPath: string;
161
/** Base path(s) to search for assets */
162
basePath?: string | string[];
163
/** Use content hash for filenames */
164
useHash?: boolean;
165
/** Hash generation options */
166
hashOptions?: HashOptions;
167
}
168
169
interface HashOptions {
170
/** Hash algorithm or custom function */
171
method?: 'xxhash32' | 'xxhash64' | string | ((content: Buffer) => string);
172
/** Number of characters to keep from hash */
173
shrink?: number;
174
/** Prepend original filename to hash */
175
append?: boolean;
176
}
177
178
// Default hash options
179
const defaultHashOptions = {
180
method: 'xxhash32',
181
shrink: 8,
182
append: false
183
};
184
```
185
186
**Basic Copy Example:**
187
188
```javascript
189
// Copy assets to specified directory
190
const result = await postcss()
191
.use(postcssUrl({
192
url: 'copy',
193
assetsPath: 'static/images'
194
}))
195
.process(css, { from: 'src/main.css', to: 'dist/main.css' });
196
197
// Before: background: url('./icon.png');
198
// After: background: url('static/images/icon.png');
199
// File copied: dist/static/images/icon.png
200
```
201
202
**Hash-based Copy Example:**
203
204
```javascript
205
// Copy with hash-based filenames
206
const result = await postcss()
207
.use(postcssUrl({
208
url: 'copy',
209
assetsPath: 'assets',
210
useHash: true,
211
hashOptions: {
212
method: 'xxhash32',
213
shrink: 8,
214
append: true // Prepend original filename
215
}
216
}))
217
.process(css, { from: 'src/main.css', to: 'dist/main.css' });
218
219
// Before: background: url('./icon.png');
220
// After: background: url('assets/icon_a1b2c3d4.png');
221
// File copied: dist/assets/icon_a1b2c3d4.png
222
```
223
224
**Crypto Hash Support:**
225
226
The plugin supports Node.js crypto module hash algorithms as well as xxhash:
227
228
```javascript
229
// Using crypto hash algorithms
230
const result = await postcss()
231
.use(postcssUrl({
232
url: 'copy',
233
assetsPath: 'assets',
234
useHash: true,
235
hashOptions: {
236
method: 'sha256', // Any Node.js crypto hash: md5, sha1, sha256, etc.
237
shrink: 16, // Keep first 16 characters
238
append: false
239
}
240
}))
241
.process(css, { from: 'src/main.css', to: 'dist/main.css' });
242
243
// Before: background: url('./icon.png');
244
// After: background: url('assets/9f86d081884c7d65.png');
245
```
246
247
### Custom Mode
248
249
Allows custom transformation functions for advanced URL processing scenarios like CDN integration or dynamic path generation.
250
251
```javascript { .api }
252
/**
253
* Custom mode configuration
254
* @param {CustomOptions} options - Custom function options
255
*/
256
interface CustomOptions {
257
url: (asset: Asset, dir: Dir, options: CustomOptions, decl: any, warn: Function, result: any, addDependency: Function) => string | Promise<string>;
258
/** Allow processing with subsequent options */
259
multi?: boolean;
260
/** Custom option properties */
261
[key: string]: any;
262
}
263
264
interface CustomFunctionParameters {
265
/** Asset information object */
266
asset: Asset;
267
/** Directory information object */
268
dir: Dir;
269
/** Current option configuration */
270
options: CustomOptions;
271
/** PostCSS declaration object */
272
decl: any;
273
/** Warning function for reporting issues */
274
warn: (message: string) => void;
275
/** PostCSS result object */
276
result: any;
277
/** Function to add file dependencies */
278
addDependency: (filePath: string) => void;
279
}
280
```
281
282
**CDN Transform Example:**
283
284
```javascript
285
// Transform URLs to CDN paths
286
const result = await postcss()
287
.use(postcssUrl({
288
url: (asset, dir, options) => {
289
if (asset.url.startsWith('/images/')) {
290
return `https://cdn.example.com${asset.url}`;
291
}
292
return asset.url; // Return unchanged
293
}
294
}))
295
.process(css, { from: 'src/main.css', to: 'dist/main.css' });
296
297
// Before: background: url('/images/hero.jpg');
298
// After: background: url('https://cdn.example.com/images/hero.jpg');
299
```
300
301
**Multi-processing Example:**
302
303
```javascript
304
// Custom function with multi-option processing
305
const result = await postcss()
306
.use(postcssUrl([
307
{
308
url: (asset, dir, options, decl, warn) => {
309
// Log all processed assets
310
console.log(`Processing: ${asset.url}`);
311
return asset.url; // Pass through unchanged
312
},
313
multi: true // Allow subsequent processing
314
},
315
{
316
url: 'copy',
317
assetsPath: 'assets'
318
}
319
]))
320
.process(css, { from: 'src/main.css', to: 'dist/main.css' });
321
```
322
323
**Async Custom Function Example:**
324
325
```javascript
326
// Async custom transformation
327
const result = await postcss()
328
.use(postcssUrl({
329
url: async (asset, dir, options) => {
330
// Async processing (e.g., API calls, file system operations)
331
const optimizedUrl = await optimizeAssetUrl(asset.url);
332
return optimizedUrl;
333
}
334
}))
335
.process(css, { from: 'src/main.css', to: 'dist/main.css' });
336
337
async function optimizeAssetUrl(url) {
338
// Custom async logic
339
return url;
340
}
341
```
342
343
## Mode Selection
344
345
The plugin automatically selects the appropriate processing mode based on configuration and provides fallback handling for error conditions.
346
347
```javascript { .api }
348
interface ModeSelection {
349
/** Default mode when no options specified */
350
default: 'rebase';
351
/** Available built-in modes */
352
modes: ['rebase', 'inline', 'copy'];
353
/** Custom function detection */
354
custom: 'typeof options.url === "function"';
355
/** Error handling for invalid modes */
356
validation: 'throws Error for unknown modes';
357
}
358
```