0
# Core Framework
1
2
Essential functions for creating, configuring, and building Nuxt applications programmatically. These APIs are primarily used for custom build processes, testing frameworks, and advanced deployment scenarios.
3
4
## Capabilities
5
6
### Create Nuxt Instance
7
8
Creates a new Nuxt instance with the provided configuration options.
9
10
```typescript { .api }
11
/**
12
* Creates a new Nuxt instance with configuration
13
* @param options - Configuration options for the Nuxt instance
14
* @returns Configured Nuxt instance with hooks and lifecycle methods
15
*/
16
function createNuxt(options: NuxtOptions): Nuxt;
17
18
interface NuxtOptions {
19
rootDir?: string;
20
srcDir?: string;
21
dev?: boolean;
22
ssr?: boolean;
23
mode?: "spa" | "universal";
24
modern?: boolean | "client" | "server";
25
head?: MetaInfo;
26
meta?: MetaInfo;
27
fetch?: {
28
server?: boolean;
29
client?: boolean;
30
};
31
features?: {
32
store?: boolean;
33
layouts?: boolean;
34
meta?: boolean;
35
middleware?: boolean;
36
transitions?: boolean;
37
deprecations?: boolean;
38
validate?: boolean;
39
asyncData?: boolean;
40
fetch?: boolean;
41
clientOnline?: boolean;
42
clientPrefetch?: boolean;
43
clientUUID?: boolean;
44
transformAssetUrls?: boolean;
45
};
46
render?: {
47
bundleRenderer?: any;
48
resourceHints?: boolean;
49
ssr?: boolean;
50
csp?: boolean | any;
51
http2?: {
52
push?: boolean;
53
shouldPush?: Function;
54
};
55
static?: any;
56
compressor?: any;
57
etag?: any;
58
dist?: any;
59
};
60
router?: {
61
base?: string;
62
mode?: "hash" | "history";
63
middleware?: string | string[];
64
linkActiveClass?: string;
65
linkExactActiveClass?: string;
66
linkPrefetchedClass?: string;
67
extendRoutes?: Function;
68
scrollBehavior?: Function;
69
parseQuery?: Function;
70
stringifyQuery?: Function;
71
fallback?: boolean;
72
prefetchLinks?: boolean;
73
prefetchPayloads?: boolean;
74
trailingSlash?: boolean;
75
};
76
dir?: {
77
assets?: string;
78
app?: string;
79
layouts?: string;
80
middleware?: string;
81
pages?: string;
82
plugins?: string;
83
static?: string;
84
store?: string;
85
};
86
[key: string]: any;
87
}
88
89
interface Nuxt {
90
options: NuxtOptions;
91
ready: () => Promise<Nuxt>;
92
hook: (name: string, fn: Function) => void;
93
callHook: (name: string, ...args: any[]) => Promise<void>;
94
addPlugin: (template: NuxtPlugin) => void;
95
addLayout: (template: NuxtTemplate, name?: string) => void;
96
addErrorLayout: (dst: string) => void;
97
addServerMiddleware: (middleware: any) => void;
98
requiredModules: { [name: string]: any };
99
close: (callback?: () => any) => Promise<void>;
100
listen: (port?: number, host?: string) => Promise<void>;
101
showReady: (showMemoryUsage?: boolean) => void;
102
render: (req: any, res: any) => Promise<void>;
103
renderRoute: (route: string, context?: any) => Promise<any>;
104
renderAndGetWindow: (url: string, opts?: any) => Promise<any>;
105
generate: (options?: any) => Promise<void>;
106
}
107
```
108
109
**Usage Examples:**
110
111
```typescript
112
import { createNuxt } from "nuxt";
113
114
// Create a basic Nuxt instance
115
const nuxt = createNuxt({
116
dev: process.env.NODE_ENV !== "production",
117
rootDir: process.cwd(),
118
srcDir: "src/"
119
});
120
121
// Create with custom configuration
122
const customNuxt = createNuxt({
123
dev: false,
124
ssr: true,
125
head: {
126
title: "My App",
127
meta: [
128
{ charset: "utf-8" },
129
{ name: "viewport", content: "width=device-width, initial-scale=1" }
130
]
131
},
132
modules: ["@nuxtjs/axios"]
133
});
134
135
// Set up hooks
136
nuxt.hook("ready", async () => {
137
console.log("Nuxt is ready");
138
});
139
140
await nuxt.ready();
141
```
142
143
### Load Nuxt Instance
144
145
Loads and initializes a Nuxt instance from configuration files with automatic config resolution.
146
147
```typescript { .api }
148
/**
149
* Loads and initializes a Nuxt instance from configuration
150
* @param opts - Loading options including config overrides
151
* @returns Promise resolving to initialized Nuxt instance
152
*/
153
function loadNuxt(opts: LoadNuxtOptions): Promise<Nuxt>;
154
155
interface LoadNuxtOptions {
156
rootDir?: string;
157
configFile?: string;
158
ready?: boolean;
159
dev?: boolean;
160
envConfig?: {
161
dotenv?: string | boolean;
162
env?: Record<string, any>;
163
};
164
for?: "dev" | "build" | "start" | "generate";
165
}
166
```
167
168
**Usage Examples:**
169
170
```typescript
171
import { loadNuxt } from "nuxt";
172
173
// Load with default configuration
174
const nuxt = await loadNuxt({
175
for: "dev"
176
});
177
178
// Load for production build
179
const buildNuxt = await loadNuxt({
180
for: "build",
181
dev: false,
182
rootDir: "/path/to/project"
183
});
184
185
// Load with custom config file
186
const customNuxt = await loadNuxt({
187
configFile: "nuxt.custom.config.js",
188
ready: true
189
});
190
191
// Load for static generation
192
const generateNuxt = await loadNuxt({
193
for: "generate",
194
dev: false
195
});
196
```
197
198
### Build Application
199
200
Builds the Nuxt application, setting up app generation, bundling, and optimization.
201
202
```typescript { .api }
203
/**
204
* Builds the Nuxt application
205
* @param nuxt - The Nuxt instance to build
206
* @returns Promise that resolves when build is complete
207
*/
208
function build(nuxt: Nuxt): Promise<void>;
209
```
210
211
**Usage Examples:**
212
213
```typescript
214
import { loadNuxt, build } from "nuxt";
215
216
// Standard build process
217
const nuxt = await loadNuxt({ for: "build" });
218
await build(nuxt);
219
await nuxt.close();
220
221
// Build with hooks
222
const nuxt = await loadNuxt({ for: "build" });
223
224
nuxt.hook("build:before", (nuxt, buildOptions) => {
225
console.log("Build starting...");
226
});
227
228
nuxt.hook("build:done", (nuxt) => {
229
console.log("Build completed!");
230
});
231
232
await build(nuxt);
233
234
// Build for different environments
235
if (process.env.ANALYZE === "true") {
236
const nuxt = await loadNuxt({
237
for: "build",
238
dev: false
239
});
240
241
// Enable bundle analyzer
242
nuxt.options.build = nuxt.options.build || {};
243
nuxt.options.build.analyze = true;
244
245
await build(nuxt);
246
await nuxt.close();
247
}
248
```
249
250
### Complete Build Workflow
251
252
```typescript
253
import { loadNuxt, build } from "nuxt";
254
255
async function buildApplication() {
256
let nuxt;
257
258
try {
259
// Load Nuxt configuration
260
nuxt = await loadNuxt({
261
for: "build",
262
rootDir: process.cwd()
263
});
264
265
// Set up build hooks
266
nuxt.hook("build:before", () => {
267
console.log("Starting build process...");
268
});
269
270
nuxt.hook("build:compile", ({ name, compiler }) => {
271
console.log(`Compiling ${name}...`);
272
});
273
274
nuxt.hook("build:compiled", ({ name, stats }) => {
275
console.log(`Compiled ${name} in ${stats.endTime - stats.startTime}ms`);
276
});
277
278
nuxt.hook("build:done", () => {
279
console.log("Build process completed!");
280
});
281
282
// Start the build
283
await build(nuxt);
284
285
console.log("✓ Build successful!");
286
287
} catch (error) {
288
console.error("Build failed:", error);
289
process.exit(1);
290
} finally {
291
// Clean up
292
if (nuxt) {
293
await nuxt.close();
294
}
295
}
296
}
297
298
// Run the build
299
buildApplication();
300
```
301
302
## Error Handling
303
304
```typescript
305
import { loadNuxt, build } from "nuxt";
306
307
async function safeBuild() {
308
let nuxt = null;
309
310
try {
311
nuxt = await loadNuxt({ for: "build" });
312
313
// Handle build errors
314
nuxt.hook("build:error", (error) => {
315
console.error("Build error:", error);
316
throw error;
317
});
318
319
await build(nuxt);
320
321
} catch (error) {
322
if (error.statusCode === 404) {
323
console.error("Configuration file not found");
324
} else if (error.name === "ModuleNotFoundError") {
325
console.error("Missing module dependency:", error.message);
326
} else {
327
console.error("Unexpected build error:", error);
328
}
329
throw error;
330
} finally {
331
if (nuxt) {
332
await nuxt.close();
333
}
334
}
335
}
336
```
337
338
## Types
339
340
```typescript { .api }
341
interface LoadNuxtConfigOptions {
342
rootDir?: string;
343
configFile?: string;
344
configContext?: any;
345
configOverrides?: any;
346
}
347
348
interface NuxtPlugin {
349
src: string;
350
fileName?: string;
351
dst?: string;
352
mode?: "client" | "server" | "all";
353
ssr?: boolean;
354
options?: any;
355
}
356
357
interface NuxtTemplate {
358
src: string;
359
fileName?: string;
360
dst?: string;
361
options?: any;
362
}
363
364
interface MetaInfo {
365
title?: string;
366
titleTemplate?: string | ((title?: string) => string);
367
meta?: any[];
368
link?: any[];
369
style?: any[];
370
script?: any[];
371
base?: any;
372
noscript?: any[];
373
__dangerouslyDisableSanitizers?: string[];
374
__dangerouslyDisableSanitizersByTagID?: { [id: string]: string[] };
375
}
376
```