0
# CSS Processing
1
2
PostCSS integration and CSS handling for both development and production builds, including plugin configuration and style optimization.
3
4
## Capabilities
5
6
### CSS Options Resolution
7
8
Resolves and configures CSS processing options including PostCSS plugins based on Nuxt configuration.
9
10
```typescript { .api }
11
/**
12
* Resolve CSS processing options including PostCSS plugins
13
* Loads and configures PostCSS plugins from Nuxt configuration
14
* @param nuxt - Nuxt instance with PostCSS configuration
15
* @returns Promise resolving to Vite CSS configuration object
16
*/
17
function resolveCSSOptions(nuxt: Nuxt): Promise<ViteConfig['css']>;
18
```
19
20
**Usage Example:**
21
22
```typescript
23
import { resolveCSSOptions } from "@nuxt/vite-builder/css";
24
import type { Nuxt } from "@nuxt/schema";
25
26
// Resolve CSS options from Nuxt configuration
27
const cssConfig = await resolveCSSOptions(nuxt);
28
29
// The returned config includes:
30
// - PostCSS plugins configuration
31
// - CSS preprocessing options
32
// - Development sourcemap settings
33
```
34
35
### PostCSS Plugin Configuration
36
37
Automatically loads and configures PostCSS plugins based on Nuxt's postcss configuration.
38
39
```typescript { .api }
40
/**
41
* PostCSS configuration structure for Vite
42
*/
43
interface PostCSSConfig {
44
/** Array of configured PostCSS plugins */
45
plugins: Plugin[];
46
}
47
48
/**
49
* PostCSS plugin sorting function
50
* @param config - PostCSS configuration with plugins and order
51
* @returns Sorted array of plugin names
52
*/
53
function sortPlugins(config: {
54
plugins: Record<string, any>;
55
order?: string[] | ((names: string[]) => string[]);
56
}): string[];
57
```
58
59
**Plugin Loading Process:**
60
61
```typescript
62
// PostCSS plugins are loaded from Nuxt configuration
63
// Example nuxt.config.ts
64
export default defineNuxtConfig({
65
postcss: {
66
plugins: {
67
'autoprefixer': {},
68
'cssnano': {
69
preset: 'default'
70
},
71
'tailwindcss': {}
72
},
73
order: ['tailwindcss', 'autoprefixer', 'cssnano']
74
}
75
});
76
```
77
78
### Plugin Resolution
79
80
Dynamically loads PostCSS plugins from the module system with proper error handling.
81
82
**Plugin Loading Features:**
83
84
- **Module Resolution**: Attempts to load plugins from multiple module directories
85
- **Error Handling**: Provides clear error messages for missing plugins
86
- **Configuration Passing**: Passes plugin-specific configuration options
87
- **Order Management**: Respects plugin execution order
88
89
```typescript
90
// Plugin loading example (internal process)
91
for (const pluginName of sortPlugins(postcssOptions)) {
92
const pluginOptions = postcssOptions.plugins[pluginName];
93
if (!pluginOptions) continue;
94
95
// Attempt to load plugin from various module directories
96
for (const parentURL of nuxt.options.modulesDir) {
97
const pluginFn = await jiti.import(pluginName, {
98
parentURL: parentURL.replace(/\/node_modules\/?$/, ''),
99
try: true,
100
default: true
101
});
102
103
if (typeof pluginFn === 'function') {
104
css.postcss.plugins.push(pluginFn(pluginOptions));
105
break;
106
}
107
}
108
}
109
```
110
111
### Built-in CSS Support
112
113
The CSS processing system includes support for various CSS preprocessors and features.
114
115
**Supported CSS Features:**
116
117
- **Native CSS**: Standard CSS with PostCSS processing
118
- **SCSS/Sass**: Sass preprocessing with variable support
119
- **Less**: Less preprocessing and compilation
120
- **Stylus**: Stylus preprocessing support
121
- **PostCSS**: Full PostCSS plugin ecosystem
122
- **CSS Modules**: Scoped CSS with module support
123
124
### Development Sourcemaps
125
126
CSS sourcemap configuration for development debugging.
127
128
```typescript
129
// CSS sourcemap configuration
130
const cssConfig = {
131
devSourcemap: !!nuxt.options.sourcemap.client, // Client sourcemaps
132
// Server-side CSS processing also respects server sourcemap settings
133
};
134
```
135
136
**Sourcemap Features:**
137
138
- **Original Source Mapping**: Maps compiled CSS back to original source files
139
- **Preprocessor Support**: Sourcemaps work with Sass, Less, and Stylus
140
- **PostCSS Integration**: Maintains sourcemaps through PostCSS transformations
141
- **Development Only**: Sourcemaps are typically disabled in production
142
143
### CSS Extraction and Inlining
144
145
Advanced CSS handling for production builds with extraction and inlining capabilities.
146
147
```typescript { .api }
148
/**
149
* SSR styles plugin options for CSS extraction
150
*/
151
interface SSRStylesPluginOptions {
152
/** Source directory for relative path resolution */
153
srcDir: string;
154
/** Set of chunk IDs that should have inlined CSS */
155
chunksWithInlinedCSS: Set<string>;
156
/** Function or boolean determining CSS inlining strategy */
157
shouldInline?: ((id?: string) => boolean) | boolean;
158
/** Component definitions for CSS extraction */
159
components: Component[];
160
/** Mapping of CSS files to client chunks */
161
clientCSSMap: Record<string, Set<string>>;
162
/** Application entry point */
163
entry: string;
164
/** Global CSS file paths */
165
globalCSS: string[];
166
/** Build mode: server or client */
167
mode: 'server' | 'client';
168
}
169
```
170
171
### CSS Optimization
172
173
Production CSS optimization including minification and purging.
174
175
**Optimization Features:**
176
177
- **Minification**: CSS minification via cssnano or similar
178
- **Purging**: Unused CSS removal (when configured)
179
- **Autoprefixing**: Automatic vendor prefix addition
180
- **Critical CSS**: Critical CSS extraction for above-the-fold content
181
- **CSS Splitting**: Automatic CSS code splitting by route
182
183
### CSS-in-JS Support
184
185
Support for CSS-in-JS solutions commonly used with Vue.js.
186
187
**Supported CSS-in-JS:**
188
189
- **Vue SFC Styles**: Scoped and module styles in Single File Components
190
- **CSS Modules**: Automatic CSS module processing
191
- **Styled Components**: Integration with styled-components (via plugins)
192
- **Emotion**: Support for Emotion CSS-in-JS (via plugins)
193
194
### Global CSS Handling
195
196
Management of global CSS files and their injection into the build.
197
198
```typescript
199
// Global CSS configuration
200
const globalCSS = [
201
'~/assets/css/main.css',
202
'~/assets/scss/variables.scss',
203
'@/styles/global.css'
204
];
205
206
// These files are:
207
// 1. Processed through PostCSS
208
// 2. Injected into the application
209
// 3. Available across all components
210
```
211
212
### CSS Asset Management
213
214
Handling of CSS-related assets like fonts, images, and other resources.
215
216
**Asset Processing:**
217
218
- **URL Resolution**: Resolves relative URLs in CSS files
219
- **Asset Optimization**: Optimizes images and fonts referenced in CSS
220
- **Public Asset Integration**: Handles assets from public directories
221
- **CDN Integration**: Supports CDN URLs for external assets
222
223
### Error Handling
224
225
Comprehensive error handling for CSS processing issues.
226
227
**Error Types Handled:**
228
229
- **Plugin Loading Errors**: Clear messages for missing PostCSS plugins
230
- **Syntax Errors**: Detailed CSS/Sass/Less syntax error reporting
231
- **Asset Resolution Errors**: Helpful messages for missing CSS assets
232
- **Configuration Errors**: Validation of PostCSS configuration
233
234
```typescript
235
// Error handling example
236
if (typeof pluginFn !== 'function') {
237
console.warn(`[nuxt] could not import postcss plugin \`${pluginName}\`. Please report this as a bug.`);
238
}
239
```