0
# Development Tools
1
2
Logging, ignore patterns, layer management, and other development utilities for building and debugging Nuxt modules.
3
4
## Capabilities
5
6
### Logging System
7
8
Structured logging with tags and configuration options.
9
10
```typescript { .api }
11
/**
12
* Create tagged logger instance
13
* @param tag - Logger tag for identification
14
* @param options - Consola configuration options
15
* @returns Configured ConsolaInstance
16
*/
17
function useLogger(
18
tag?: string,
19
options?: Partial<ConsolaOptions>
20
): ConsolaInstance;
21
22
/**
23
* Default Consola logger instance
24
*/
25
const logger: ConsolaInstance;
26
27
interface ConsolaInstance {
28
/** Log informational message */
29
info(...args: any[]): void;
30
/** Log warning message */
31
warn(...args: any[]): void;
32
/** Log error message */
33
error(...args: any[]): void;
34
/** Log debug message */
35
debug(...args: any[]): void;
36
/** Log success message */
37
success(...args: any[]): void;
38
/** Log fatal error and exit */
39
fatal(...args: any[]): void;
40
/** Log trace message */
41
trace(...args: any[]): void;
42
/** Log with custom level */
43
log(...args: any[]): void;
44
/** Create child logger */
45
withTag(tag: string): ConsolaInstance;
46
}
47
48
interface ConsolaOptions {
49
/** Log level */
50
level?: number;
51
/** Reporter configuration */
52
reporters?: any[];
53
/** Custom log types */
54
types?: Record<string, any>;
55
/** Throttle options */
56
throttle?: number;
57
[key: string]: any;
58
}
59
```
60
61
**Usage Examples:**
62
63
```typescript
64
import { useLogger, logger } from "@nuxt/kit";
65
66
// Use default logger
67
logger.info("Module initialized");
68
logger.warn("Deprecated option used");
69
logger.error("Configuration error");
70
71
// Create tagged logger
72
const moduleLogger = useLogger("my-module");
73
moduleLogger.info("Module-specific message");
74
75
// Logger with custom options
76
const debugLogger = useLogger("debug", {
77
level: 4, // Enable debug messages
78
reporters: [
79
{
80
log: (logObj) => {
81
console.log(`[${logObj.tag}] ${logObj.message}`);
82
}
83
}
84
]
85
});
86
87
// Module with logger
88
export default defineNuxtModule({
89
meta: {
90
name: "my-module"
91
},
92
setup(options, nuxt) {
93
const logger = useLogger("my-module");
94
95
logger.info("Setting up module...");
96
97
if (options.debug) {
98
logger.debug("Debug mode enabled");
99
}
100
101
try {
102
// Module setup logic
103
logger.success("Module setup complete");
104
} catch (error) {
105
logger.error("Module setup failed:", error);
106
throw error;
107
}
108
}
109
});
110
```
111
112
### Ignore Pattern System
113
114
Path filtering and ignore pattern management based on .nuxtignore and configuration.
115
116
```typescript { .api }
117
/**
118
* Check if path should be ignored based on .nuxtignore and patterns
119
* @param pathname - Path to check
120
* @param stats - Optional file stats
121
* @param nuxt - Nuxt instance (defaults to current context)
122
* @returns True if path should be ignored
123
*/
124
function isIgnored(
125
pathname: string,
126
stats?: unknown,
127
nuxt?: Nuxt
128
): boolean;
129
130
/**
131
* Create ignore function with Nuxt context
132
* @param nuxt - Nuxt instance (defaults to current context)
133
* @returns Function to check if path should be ignored
134
*/
135
function createIsIgnored(nuxt?: Nuxt): (pathname: string, stats?: unknown) => boolean;
136
137
/**
138
* Resolve ignore patterns from configuration and .nuxtignore
139
* @param relativePath - Relative path for context
140
* @returns Array of ignore patterns
141
*/
142
function resolveIgnorePatterns(relativePath?: string): string[];
143
```
144
145
**Usage Examples:**
146
147
```typescript
148
import {
149
isIgnored,
150
createIsIgnored,
151
resolveIgnorePatterns
152
} from "@nuxt/kit";
153
154
// Check individual paths
155
const shouldIgnore = isIgnored("node_modules/package");
156
const shouldIgnoreComponent = isIgnored("components/internal/Debug.vue");
157
158
// Create reusable ignore checker
159
const ignoreChecker = createIsIgnored();
160
161
const filesToProcess = [
162
"components/Button.vue",
163
"components/internal/Debug.vue",
164
"node_modules/library/index.js",
165
".nuxt/dist/app.js"
166
];
167
168
const validFiles = filesToProcess.filter(file => !ignoreChecker(file));
169
170
// Get current ignore patterns
171
const patterns = resolveIgnorePatterns();
172
console.log("Active ignore patterns:", patterns);
173
174
// Module with ignore pattern support
175
export default defineNuxtModule({
176
setup(options, nuxt) {
177
const logger = useLogger("file-processor");
178
const shouldIgnore = createIsIgnored();
179
180
// Process files excluding ignored ones
181
const processFile = (filepath: string) => {
182
if (shouldIgnore(filepath)) {
183
logger.debug(`Skipping ignored file: ${filepath}`);
184
return;
185
}
186
187
logger.info(`Processing: ${filepath}`);
188
// Process file...
189
};
190
}
191
});
192
```
193
194
### Layer Management
195
196
Work with Nuxt layers and access layer directory information.
197
198
```typescript { .api }
199
/**
200
* Get resolved directory paths for all layers in priority order
201
* @param nuxt - Nuxt instance (defaults to current context)
202
* @returns Array of LayerDirectories objects
203
*/
204
function getLayerDirectories(nuxt?: Nuxt): LayerDirectories[];
205
206
interface LayerDirectories {
207
/** Nuxt rootDir (`/` by default) */
208
readonly root: string;
209
/** Nitro source directory (`/server` by default) */
210
readonly server: string;
211
/** Local modules directory (`/modules` by default) */
212
readonly modules: string;
213
/** Shared directory (`/shared` by default) */
214
readonly shared: string;
215
/** Public directory (`/public` by default) */
216
readonly public: string;
217
/** Nuxt srcDir (`/app/` by default) */
218
readonly app: string;
219
/** Layouts directory (`/app/layouts` by default) */
220
readonly appLayouts: string;
221
/** Middleware directory (`/app/middleware` by default) */
222
readonly appMiddleware: string;
223
/** Pages directory (`/app/pages` by default) */
224
readonly appPages: string;
225
/** Plugins directory (`/app/plugins` by default) */
226
readonly appPlugins: string;
227
}
228
```
229
230
**Usage Examples:**
231
232
```typescript
233
import { getLayerDirectories, addComponentsDir } from "@nuxt/kit";
234
235
// Get all layer directories
236
const layers = getLayerDirectories();
237
238
layers.forEach((layer, index) => {
239
console.log(`Layer ${index}: ${layer.root}`);
240
console.log(` App: ${layer.app}`);
241
console.log(` Layouts: ${layer.appLayouts}`);
242
console.log(` Pages: ${layer.appPages}`);
243
console.log(` Plugins: ${layer.appPlugins}`);
244
});
245
246
// Module that works with layers
247
export default defineNuxtModule({
248
setup(options, nuxt) {
249
const logger = useLogger("layer-processor");
250
const layers = getLayerDirectories();
251
252
// Process components from all layers
253
layers.forEach((layer, index) => {
254
logger.info(`Processing layer ${index}: ${layer.root}`);
255
256
// Add components from each layer if components directory exists
257
const componentsPath = join(layer.app, "components");
258
if (existsSync(componentsPath)) {
259
addComponentsDir({
260
path: componentsPath,
261
prefix: `Layer${index}`,
262
priority: layers.length - index // Higher priority for later layers
263
});
264
}
265
266
// Check for layer-specific configuration
267
const layerConfig = join(layer.root, "layer.config.ts");
268
if (existsSync(layerConfig)) {
269
logger.info(`Found layer config: ${layerConfig}`);
270
// Process layer config...
271
}
272
});
273
}
274
});
275
```
276
277
### Layout Management
278
279
Add and manage layout templates.
280
281
```typescript { .api }
282
/**
283
* Add a layout template with optional name
284
* @param template - Layout template configuration or file path
285
* @param name - Optional layout name
286
*/
287
function addLayout(template: NuxtTemplate | string, name?: string): void;
288
```
289
290
**Usage Examples:**
291
292
```typescript
293
import { addLayout } from "@nuxt/kit";
294
295
// Add layout from file
296
addLayout("~/layouts/custom.vue", "custom");
297
298
// Add layout with template
299
addLayout({
300
src: "~/templates/admin-layout.vue",
301
filename: "layouts/admin.vue"
302
}, "admin");
303
304
// Module adding layouts
305
export default defineNuxtModule({
306
setup(options, nuxt) {
307
const resolver = createResolver(import.meta.url);
308
309
// Add module layouts
310
addLayout(resolver.resolve("./runtime/layouts/dashboard.vue"), "dashboard");
311
addLayout(resolver.resolve("./runtime/layouts/minimal.vue"), "minimal");
312
}
313
});
314
```
315
316
### Pages & Routing Utilities
317
318
Extend pages configuration and route rules.
319
320
```typescript { .api }
321
/**
322
* Add route middleware
323
* @param input - Middleware configuration or array
324
* @param options - Middleware options
325
*/
326
function addRouteMiddleware(
327
input: NuxtMiddleware | NuxtMiddleware[],
328
options?: AddRouteMiddlewareOptions
329
): void;
330
331
/**
332
* Extend pages configuration
333
* @param cb - Callback to modify pages array
334
*/
335
function extendPages(cb: NuxtHooks['pages:extend']): void;
336
337
/**
338
* Extend route rules configuration
339
* @param route - Route pattern
340
* @param rule - Route rule configuration
341
* @param options - Extension options
342
*/
343
function extendRouteRules(
344
route: string,
345
rule: NitroRouteConfig,
346
options?: ExtendRouteRulesOptions
347
): void;
348
349
interface NuxtMiddleware {
350
/** Middleware name */
351
name: string;
352
/** Middleware file path */
353
path: string;
354
/** Global middleware flag */
355
global?: boolean;
356
}
357
358
interface AddRouteMiddlewareOptions {
359
/** Override existing middleware */
360
override?: boolean;
361
}
362
363
interface ExtendRouteRulesOptions {
364
/** Override existing rules */
365
override?: boolean;
366
}
367
```
368
369
**Usage Examples:**
370
371
```typescript
372
import {
373
addRouteMiddleware,
374
extendPages,
375
extendRouteRules
376
} from "@nuxt/kit";
377
378
// Add route middleware
379
addRouteMiddleware({
380
name: "auth",
381
path: "~/middleware/auth.ts",
382
global: false
383
});
384
385
// Add global middleware
386
addRouteMiddleware({
387
name: "analytics",
388
path: "~/middleware/analytics.global.ts",
389
global: true
390
});
391
392
// Extend pages
393
extendPages((pages) => {
394
// Add custom page
395
pages.push({
396
name: "custom-admin",
397
path: "/admin/custom",
398
file: "~/pages/admin/custom.vue"
399
});
400
401
// Modify existing pages
402
pages.forEach(page => {
403
if (page.path.startsWith("/admin")) {
404
page.meta = page.meta || {};
405
page.meta.requiresAuth = true;
406
}
407
});
408
});
409
410
// Extend route rules
411
extendRouteRules("/api/**", {
412
cors: true,
413
headers: {
414
"Access-Control-Allow-Origin": "*"
415
}
416
});
417
418
extendRouteRules("/admin/**", {
419
ssr: false,
420
prerender: false
421
});
422
```
423
424
### Advanced Development Patterns
425
426
**Module with Development Mode Features:**
427
428
```typescript
429
import { useLogger, isIgnored } from "@nuxt/kit";
430
431
export default defineNuxtModule({
432
setup(options, nuxt) {
433
const logger = useLogger("dev-module");
434
435
if (nuxt.options.dev) {
436
logger.info("Development mode features enabled");
437
438
// Add development-only components
439
addComponentsDir({
440
path: "~/components/dev",
441
global: true,
442
watch: true
443
});
444
445
// Add hot-reload support
446
nuxt.hook("builder:watch", (event, path) => {
447
if (!isIgnored(path) && path.includes("custom-config")) {
448
logger.info(`Reloading due to change in: ${path}`);
449
// Trigger reload
450
}
451
});
452
}
453
}
454
});
455
```
456
457
**Layer-Aware Component Processing:**
458
459
```typescript
460
import { getLayerDirectories, addComponentsDir, useLogger } from "@nuxt/kit";
461
462
export default defineNuxtModule({
463
setup() {
464
const logger = useLogger("layer-components");
465
const layers = getLayerDirectories();
466
467
// Process each layer with priority
468
layers.forEach((layer, index) => {
469
const priority = layers.length - index;
470
471
logger.info(`Processing layer ${index} (priority: ${priority})`);
472
473
// Add themed components if theme directory exists
474
const themeDir = join(layer.app, "components", "theme");
475
if (existsSync(themeDir)) {
476
addComponentsDir({
477
path: themeDir,
478
prefix: "Theme",
479
priority,
480
global: true
481
});
482
}
483
});
484
}
485
});
486
```
487
488
## Types
489
490
```typescript { .api }
491
interface NuxtHooks {
492
'pages:extend': (pages: NuxtPage[]) => void;
493
'builder:watch': (event: string, path: string) => void;
494
[key: string]: (...args: any[]) => any;
495
}
496
497
interface NuxtPage {
498
/** Page name */
499
name?: string;
500
/** Page path */
501
path: string;
502
/** Page file */
503
file?: string;
504
/** Page metadata */
505
meta?: Record<string, any>;
506
/** Child pages */
507
children?: NuxtPage[];
508
}
509
510
interface NitroRouteConfig {
511
/** Server-side rendering */
512
ssr?: boolean;
513
/** Prerendering */
514
prerender?: boolean;
515
/** CORS configuration */
516
cors?: boolean;
517
/** Response headers */
518
headers?: Record<string, string>;
519
/** Route priority */
520
priority?: number;
521
[key: string]: any;
522
}
523
```