0
# @tailwindcss/postcss
1
2
@tailwindcss/postcss is a PostCSS plugin that integrates Tailwind CSS v4 into PostCSS-based build pipelines. It provides automated class candidate scanning, CSS compilation, optimization, and intelligent caching with dependency tracking for high-performance builds.
3
4
## Package Information
5
6
- **Package Name**: @tailwindcss/postcss
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @tailwindcss/postcss`
10
11
## Core Imports
12
13
```typescript
14
import tailwindcss from "@tailwindcss/postcss";
15
import { cssAstToPostCssAst, postCssAstToCssAst } from "@tailwindcss/postcss/ast";
16
```
17
18
For CommonJS:
19
20
```javascript
21
const tailwindcss = require("@tailwindcss/postcss");
22
const { cssAstToPostCssAst, postCssAstToCssAst } = require("@tailwindcss/postcss/ast");
23
24
// Note: The package uses `export =` syntax for CommonJS compatibility
25
// This ensures proper integration with postcss-load-config
26
```
27
28
## Basic Usage
29
30
```typescript
31
import postcss from "postcss";
32
import tailwindcss from "@tailwindcss/postcss";
33
34
// Basic configuration
35
const processor = postcss([
36
tailwindcss({
37
base: "./src",
38
optimize: true,
39
})
40
]);
41
42
// Process CSS with Tailwind
43
const result = await processor.process(`
44
@import 'tailwindcss';
45
46
.custom-button {
47
@apply bg-blue-500 text-white px-4 py-2 rounded;
48
}
49
`, { from: "input.css" });
50
51
console.log(result.css);
52
```
53
54
## Architecture
55
56
@tailwindcss/postcss implements a sophisticated two-stage PostCSS processing pipeline:
57
58
- **Stage 1: Path Resolution**: Handles relative path corrections for imported files
59
- **Stage 2: Core Processing**: Scans for class candidates, compiles Tailwind CSS, and applies optimizations
60
61
Key architectural components:
62
63
- **Intelligent Caching**: LRU cache with file modification time tracking for incremental builds
64
- **Rust-based Scanning**: Uses @tailwindcss/oxide for high-performance candidate detection
65
- **AST Transformation**: Bidirectional conversion between PostCSS and Tailwind CSS ASTs
66
- **Lightning CSS Optimization**: Advanced CSS optimization and minification
67
- **Dependency Tracking**: Automatic dependency registration for proper rebuild triggers
68
69
## Capabilities
70
71
### PostCSS Plugin Factory
72
73
Creates the main PostCSS plugin with configurable options for Tailwind CSS processing.
74
75
```typescript { .api }
76
/**
77
* Creates a PostCSS plugin for Tailwind CSS v4 processing
78
* @param opts - Configuration options for the plugin
79
* @returns PostCSS plugin with Tailwind CSS processing capabilities
80
*/
81
function tailwindcss(opts?: PluginOptions): AcceptedPlugin;
82
83
/**
84
* Default export is the tailwindcss function with postcss property
85
* The plugin function includes a postcss property set to true for PostCSS compatibility
86
*/
87
declare const _default: typeof tailwindcss & { postcss: true };
88
export default _default;
89
90
interface PluginOptions {
91
/**
92
* The base directory to scan for class candidates.
93
* Defaults to the current working directory.
94
*/
95
base?: string;
96
97
/**
98
* Optimize and minify the output CSS.
99
* Can be boolean or object with minify option.
100
* Defaults to true in production (NODE_ENV === 'production').
101
*/
102
optimize?: boolean | { minify?: boolean };
103
104
/**
105
* Enable or disable asset URL rewriting.
106
* Defaults to true.
107
*/
108
transformAssetUrls?: boolean;
109
}
110
111
/**
112
* PostCSS AcceptedPlugin interface
113
*/
114
interface AcceptedPlugin {
115
postcssPlugin: string;
116
plugins: Plugin[];
117
}
118
119
/**
120
* PostCSS Plugin interface
121
*/
122
interface Plugin {
123
postcssPlugin: string;
124
Once?: (root: Root, helpers: { result: Result }) => void | Promise<void>;
125
OnceExit?: (root: Root, helpers: { result: Result }) => void | Promise<void>;
126
[key: string]: any;
127
}
128
```
129
130
### AST Transformation Functions
131
132
Functions for converting between PostCSS and Tailwind CSS AST formats, useful for advanced integrations and plugin development.
133
134
```typescript { .api }
135
/**
136
* Converts Tailwind CSS AST nodes to PostCSS AST format
137
* @param ast - Array of Tailwind CSS AST nodes
138
* @param source - PostCSS source object for source mapping
139
* @returns PostCSS Root node containing the converted AST
140
*/
141
function cssAstToPostCssAst(ast: AstNode[], source: PostcssSource | undefined): Root;
142
143
/**
144
* Converts PostCSS AST to Tailwind CSS AST format
145
* @param root - PostCSS Root node to convert
146
* @returns Array of Tailwind CSS AST nodes
147
*/
148
function postCssAstToCssAst(root: Root): AstNode[];
149
150
/**
151
* Tailwind CSS AST node types
152
*/
153
type AstNode = Declaration | Rule | AtRule | Comment;
154
155
interface Declaration {
156
kind: 'declaration';
157
property: string;
158
value: string;
159
important: boolean;
160
src?: SourceLocation;
161
}
162
163
interface Rule {
164
kind: 'rule';
165
selector: string;
166
nodes: AstNode[];
167
src?: SourceLocation;
168
}
169
170
interface AtRule {
171
kind: 'at-rule';
172
name: string;
173
params: string;
174
nodes: AstNode[];
175
src?: SourceLocation;
176
}
177
178
interface Comment {
179
kind: 'comment';
180
value: string;
181
src?: SourceLocation;
182
}
183
184
type SourceLocation = [Source, number, number];
185
186
interface Source {
187
file: string | null;
188
code: string;
189
}
190
191
/**
192
* PostCSS source interface
193
*/
194
interface PostcssSource {
195
input: Input;
196
start: Position;
197
end: Position;
198
}
199
200
interface Position {
201
line: number;
202
column: number;
203
offset: number;
204
}
205
206
interface Input {
207
css: string;
208
file?: string;
209
id?: string;
210
map?: any;
211
}
212
213
/**
214
* PostCSS Root and related interfaces
215
*/
216
interface Root {
217
type: 'root';
218
nodes: ChildNode[];
219
source?: PostcssSource;
220
removeAll(): void;
221
append(node: ChildNode | ChildNode[]): void;
222
clone(): Root;
223
each(callback: (node: ChildNode) => void): void;
224
}
225
226
type ChildNode = Rule | AtRule | Declaration | Comment;
227
```
228
229
## Usage Examples
230
231
### Development Mode Configuration
232
233
```typescript
234
import postcss from "postcss";
235
import tailwindcss from "@tailwindcss/postcss";
236
237
const processor = postcss([
238
tailwindcss({
239
base: "./src",
240
optimize: false, // Disable optimization for faster builds
241
transformAssetUrls: true,
242
})
243
]);
244
```
245
246
### Production Mode Configuration
247
248
```typescript
249
import postcss from "postcss";
250
import tailwindcss from "@tailwindcss/postcss";
251
252
const processor = postcss([
253
tailwindcss({
254
base: "./src",
255
optimize: { minify: true }, // Enable full optimization
256
transformAssetUrls: true,
257
})
258
]);
259
```
260
261
### PostCSS Configuration File
262
263
```javascript
264
// postcss.config.js
265
module.exports = {
266
plugins: [
267
require("@tailwindcss/postcss")({
268
base: process.cwd(),
269
optimize: process.env.NODE_ENV === "production",
270
}),
271
],
272
};
273
```
274
275
### Vite Configuration
276
277
```typescript
278
// vite.config.ts
279
import { defineConfig } from "vite";
280
281
export default defineConfig({
282
css: {
283
postcss: {
284
plugins: [
285
require("@tailwindcss/postcss")({
286
base: "./src",
287
}),
288
],
289
},
290
},
291
});
292
```
293
294
### Webpack Configuration
295
296
```javascript
297
// webpack.config.js
298
module.exports = {
299
module: {
300
rules: [
301
{
302
test: /\.css$/,
303
use: [
304
"style-loader",
305
"css-loader",
306
{
307
loader: "postcss-loader",
308
options: {
309
postcssOptions: {
310
plugins: [
311
require("@tailwindcss/postcss")({
312
base: "./src",
313
}),
314
],
315
},
316
},
317
},
318
],
319
},
320
],
321
},
322
};
323
```
324
325
### AST Transformation Usage
326
327
```typescript
328
import { cssAstToPostCssAst, postCssAstToCssAst } from "@tailwindcss/postcss/ast";
329
import postcss from "postcss";
330
331
// Convert PostCSS AST to Tailwind CSS AST
332
const postcssRoot = postcss.parse(`
333
.test {
334
color: red;
335
}
336
`);
337
338
const tailwindAst = postCssAstToCssAst(postcssRoot);
339
console.log('Tailwind AST:', tailwindAst);
340
341
// Convert back to PostCSS AST
342
const convertedRoot = cssAstToPostCssAst(tailwindAst, postcssRoot.source);
343
console.log('Converted PostCSS AST:', convertedRoot.toString());
344
```
345
346
## Performance Features
347
348
### Intelligent Caching
349
- LRU cache with configurable size (default: 50 entries)
350
- File modification time tracking for incremental builds
351
- Automatic cache invalidation on errors or dependency changes
352
353
### Incremental Compilation
354
- Dependency tracking with PostCSS message system
355
- Selective rebuilds based on file changes
356
- Full rebuild triggers for configuration changes
357
358
### High-Performance Scanning
359
- Rust-based Oxide scanner for fast candidate detection
360
- Configurable source patterns and negation support
361
- Automatic glob-based dependency registration
362
363
### CSS Optimization
364
- Lightning CSS integration for advanced optimization
365
- Optional minification with production defaults
366
- Asset URL rewriting with configurable toggle
367
368
## Error Handling
369
370
The plugin implements graceful error handling:
371
372
- **Compilation Errors**: Logs errors and returns empty stylesheet to prevent PostCSS crashes
373
- **File System Errors**: Handles missing files and permission issues gracefully
374
- **Cache Invalidation**: Automatically clears cache on errors to ensure clean rebuilds
375
- **Dependency Tracking**: Continues to track dependencies even when errors occur
376
377
```typescript
378
// Example error handling in usage
379
try {
380
const result = await processor.process(css, { from: "input.css" });
381
console.log(result.css);
382
} catch (error) {
383
// Plugin logs errors internally and returns empty CSS
384
// PostCSS processing continues without crashing
385
console.log("Processing completed with fallback");
386
}
387
```
388
389
## Build Tool Integration
390
391
### Next.js
392
393
```javascript
394
// next.config.js
395
module.exports = {
396
experimental: {
397
// Next.js automatically configures PostCSS
398
// Place postcss.config.js in project root
399
},
400
};
401
```
402
403
### Parcel
404
405
```json
406
// package.json
407
{
408
"browserslist": ["> 1%", "last 2 versions"],
409
"@parcel/transformer-css": {
410
"drafts": {
411
"customMedia": true
412
}
413
}
414
}
415
```
416
417
### Rollup
418
419
```javascript
420
// rollup.config.js
421
import postcss from "rollup-plugin-postcss";
422
423
export default {
424
plugins: [
425
postcss({
426
plugins: [
427
require("@tailwindcss/postcss")({
428
base: "./src",
429
}),
430
],
431
}),
432
],
433
};
434
```