0
# Main Bundling
1
2
Core bundling functionality that orchestrates the entire build process for both client and server targets in Nuxt applications.
3
4
## Capabilities
5
6
### Bundle Function
7
8
The primary export that handles the complete build process for Nuxt applications using Vite.
9
10
```typescript { .api }
11
/**
12
* Main bundling function for Nuxt applications using Vite
13
* Configures and executes both client and server builds with optimized settings
14
* @param nuxt - Nuxt instance containing configuration and build context
15
*/
16
function bundle(nuxt: Nuxt): Promise<void>;
17
```
18
19
**Usage Example:**
20
21
```typescript
22
import type { Nuxt } from "@nuxt/schema";
23
import { bundle } from "@nuxt/vite-builder";
24
25
// Assuming you have a configured Nuxt instance
26
const nuxt: Nuxt = await loadNuxt({ for: 'build' });
27
28
// Execute the complete build process
29
await bundle(nuxt);
30
31
// This will:
32
// 1. Configure Vite settings for both client and server
33
// 2. Set up development servers (if in dev mode)
34
// 3. Configure all necessary plugins
35
// 4. Execute client build
36
// 5. Execute server build
37
// 6. Generate manifests
38
```
39
40
### Build Context Creation
41
42
The bundle function creates and manages the ViteBuildContext throughout the build process.
43
44
```typescript { .api }
45
interface ViteBuildContext {
46
/** Nuxt application instance containing all configuration */
47
nuxt: Nuxt;
48
/** Merged Vite configuration for the build */
49
config: ViteConfig;
50
/** Resolved path to the application entry file */
51
entry: string;
52
/** Optional Vite development server for client-side assets */
53
clientServer?: ViteDevServer;
54
/** Optional Vite development server for SSR assets */
55
ssrServer?: ViteDevServer;
56
}
57
```
58
59
### Configuration Merging
60
61
The bundle function performs sophisticated configuration merging between Nuxt and Vite settings.
62
63
**Key Configuration Areas:**
64
65
- **Resolve Aliases**: Maps Nuxt directory aliases to absolute paths
66
- **Build Options**: Configures output directories, chunk naming, and sourcemaps
67
- **CSS Processing**: Integrates PostCSS plugins and CSS handling
68
- **Plugin Registration**: Adds all necessary Vite plugins for Nuxt functionality
69
- **Development Settings**: Configures file watching, HMR, and dev server options
70
71
**Core Configuration Applied:**
72
73
```typescript
74
// Example of key configuration areas managed by bundle()
75
const viteConfig = {
76
resolve: {
77
alias: {
78
'#app': nuxt.options.appDir,
79
// Asset directory aliases
80
[basename(nuxt.options.dir.assets)]: resolve(nuxt.options.srcDir, nuxt.options.dir.assets),
81
// All user-defined aliases from nuxt.config
82
...nuxt.options.alias,
83
},
84
},
85
define: {
86
__NUXT_VERSION__: JSON.stringify(nuxt._version),
87
__NUXT_ASYNC_CONTEXT__: nuxt.options.experimental.asyncContext,
88
},
89
build: {
90
rollupOptions: {
91
output: {
92
sanitizeFileName: sanitizeFilePath,
93
assetFileNames: // Configures asset naming with hash patterns
94
},
95
},
96
},
97
plugins: [
98
// All Nuxt-specific Vite plugins
99
],
100
};
101
```
102
103
### Hook Integration
104
105
The bundle function integrates with Nuxt's hook system for extensibility.
106
107
**Key Hooks Called:**
108
109
- `vite:extend` - Allows modification of the build context before processing
110
- `vite:extendConfig` - Enables configuration modifications for both client and server
111
- `vite:serverCreated` - Called when development servers are created
112
- `vite:compiled` - Triggered after successful compilation
113
114
**Hook Usage Example:**
115
116
```typescript
117
// In a Nuxt module or plugin
118
nuxt.hook('vite:extendConfig', (config, { isClient, isServer }) => {
119
if (isClient) {
120
// Modify client-specific configuration
121
config.plugins.push(myClientPlugin());
122
}
123
if (isServer) {
124
// Modify server-specific configuration
125
config.plugins.push(myServerPlugin());
126
}
127
});
128
```
129
130
### Development vs Production
131
132
The bundle function automatically adapts behavior based on `nuxt.options.dev`:
133
134
**Development Mode:**
135
- Creates Vite dev servers with HMR
136
- Enables file watching and fast refresh
137
- Uses in-memory compilation
138
- Provides detailed logging and error reporting
139
140
**Production Mode:**
141
- Generates static bundled files
142
- Applies minification and optimization
143
- Creates asset manifests
144
- Performs code splitting and chunk optimization
145
146
### Error Handling
147
148
The bundle function includes comprehensive error handling and logging:
149
150
- **Configuration Validation**: Ensures all required options are present
151
- **Plugin Error Recovery**: Gracefully handles plugin initialization failures
152
- **Build Error Reporting**: Provides detailed error messages with context
153
- **Performance Monitoring**: Logs build times and performance metrics