CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-nuxt--kit

Toolkit for authoring modules and interacting with Nuxt

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

development-tools.mddocs/

Development Tools

Logging, ignore patterns, layer management, and other development utilities for building and debugging Nuxt modules.

Capabilities

Logging System

Structured logging with tags and configuration options.

/**
 * Create tagged logger instance
 * @param tag - Logger tag for identification
 * @param options - Consola configuration options
 * @returns Configured ConsolaInstance
 */
function useLogger(
  tag?: string,
  options?: Partial<ConsolaOptions>
): ConsolaInstance;

/**
 * Default Consola logger instance
 */
const logger: ConsolaInstance;

interface ConsolaInstance {
  /** Log informational message */
  info(...args: any[]): void;
  /** Log warning message */
  warn(...args: any[]): void;
  /** Log error message */
  error(...args: any[]): void;
  /** Log debug message */
  debug(...args: any[]): void;
  /** Log success message */
  success(...args: any[]): void;
  /** Log fatal error and exit */
  fatal(...args: any[]): void;
  /** Log trace message */
  trace(...args: any[]): void;
  /** Log with custom level */
  log(...args: any[]): void;
  /** Create child logger */
  withTag(tag: string): ConsolaInstance;
}

interface ConsolaOptions {
  /** Log level */
  level?: number;
  /** Reporter configuration */
  reporters?: any[];
  /** Custom log types */
  types?: Record<string, any>;
  /** Throttle options */
  throttle?: number;
  [key: string]: any;
}

Usage Examples:

import { useLogger, logger } from "@nuxt/kit";

// Use default logger
logger.info("Module initialized");
logger.warn("Deprecated option used");
logger.error("Configuration error");

// Create tagged logger
const moduleLogger = useLogger("my-module");
moduleLogger.info("Module-specific message");

// Logger with custom options
const debugLogger = useLogger("debug", {
  level: 4, // Enable debug messages
  reporters: [
    {
      log: (logObj) => {
        console.log(`[${logObj.tag}] ${logObj.message}`);
      }
    }
  ]
});

// Module with logger
export default defineNuxtModule({
  meta: {
    name: "my-module"
  },
  setup(options, nuxt) {
    const logger = useLogger("my-module");
    
    logger.info("Setting up module...");
    
    if (options.debug) {
      logger.debug("Debug mode enabled");
    }
    
    try {
      // Module setup logic
      logger.success("Module setup complete");
    } catch (error) {
      logger.error("Module setup failed:", error);
      throw error;
    }
  }
});

Ignore Pattern System

Path filtering and ignore pattern management based on .nuxtignore and configuration.

/**
 * Check if path should be ignored based on .nuxtignore and patterns
 * @param pathname - Path to check
 * @param stats - Optional file stats
 * @param nuxt - Nuxt instance (defaults to current context)
 * @returns True if path should be ignored
 */
function isIgnored(
  pathname: string,
  stats?: unknown,
  nuxt?: Nuxt
): boolean;

/**
 * Create ignore function with Nuxt context
 * @param nuxt - Nuxt instance (defaults to current context)
 * @returns Function to check if path should be ignored
 */
function createIsIgnored(nuxt?: Nuxt): (pathname: string, stats?: unknown) => boolean;

/**
 * Resolve ignore patterns from configuration and .nuxtignore
 * @param relativePath - Relative path for context
 * @returns Array of ignore patterns
 */
function resolveIgnorePatterns(relativePath?: string): string[];

Usage Examples:

import { 
  isIgnored, 
  createIsIgnored, 
  resolveIgnorePatterns 
} from "@nuxt/kit";

// Check individual paths
const shouldIgnore = isIgnored("node_modules/package");
const shouldIgnoreComponent = isIgnored("components/internal/Debug.vue");

// Create reusable ignore checker
const ignoreChecker = createIsIgnored();

const filesToProcess = [
  "components/Button.vue",
  "components/internal/Debug.vue",
  "node_modules/library/index.js",
  ".nuxt/dist/app.js"
];

const validFiles = filesToProcess.filter(file => !ignoreChecker(file));

// Get current ignore patterns
const patterns = resolveIgnorePatterns();
console.log("Active ignore patterns:", patterns);

// Module with ignore pattern support
export default defineNuxtModule({
  setup(options, nuxt) {
    const logger = useLogger("file-processor");
    const shouldIgnore = createIsIgnored();
    
    // Process files excluding ignored ones
    const processFile = (filepath: string) => {
      if (shouldIgnore(filepath)) {
        logger.debug(`Skipping ignored file: ${filepath}`);
        return;
      }
      
      logger.info(`Processing: ${filepath}`);
      // Process file...
    };
  }
});

Layer Management

Work with Nuxt layers and access layer directory information.

/**
 * Get resolved directory paths for all layers in priority order
 * @param nuxt - Nuxt instance (defaults to current context)
 * @returns Array of LayerDirectories objects
 */
function getLayerDirectories(nuxt?: Nuxt): LayerDirectories[];

interface LayerDirectories {
  /** Nuxt rootDir (`/` by default) */
  readonly root: string;
  /** Nitro source directory (`/server` by default) */
  readonly server: string;
  /** Local modules directory (`/modules` by default) */
  readonly modules: string;
  /** Shared directory (`/shared` by default) */
  readonly shared: string;
  /** Public directory (`/public` by default) */
  readonly public: string;
  /** Nuxt srcDir (`/app/` by default) */
  readonly app: string;
  /** Layouts directory (`/app/layouts` by default) */
  readonly appLayouts: string;
  /** Middleware directory (`/app/middleware` by default) */
  readonly appMiddleware: string;
  /** Pages directory (`/app/pages` by default) */
  readonly appPages: string;
  /** Plugins directory (`/app/plugins` by default) */
  readonly appPlugins: string;
}

Usage Examples:

import { getLayerDirectories, addComponentsDir } from "@nuxt/kit";

// Get all layer directories
const layers = getLayerDirectories();

layers.forEach((layer, index) => {
  console.log(`Layer ${index}: ${layer.root}`);
  console.log(`  App: ${layer.app}`);
  console.log(`  Layouts: ${layer.appLayouts}`);
  console.log(`  Pages: ${layer.appPages}`);
  console.log(`  Plugins: ${layer.appPlugins}`);
});

// Module that works with layers
export default defineNuxtModule({
  setup(options, nuxt) {
    const logger = useLogger("layer-processor");
    const layers = getLayerDirectories();
    
    // Process components from all layers
    layers.forEach((layer, index) => {
      logger.info(`Processing layer ${index}: ${layer.root}`);
      
      // Add components from each layer if components directory exists
      const componentsPath = join(layer.app, "components");
      if (existsSync(componentsPath)) {
        addComponentsDir({
          path: componentsPath,
          prefix: `Layer${index}`,
          priority: layers.length - index // Higher priority for later layers
        });
      }
      
      // Check for layer-specific configuration
      const layerConfig = join(layer.root, "layer.config.ts");
      if (existsSync(layerConfig)) {
        logger.info(`Found layer config: ${layerConfig}`);
        // Process layer config...
      }
    });
  }
});

Layout Management

Add and manage layout templates.

/**
 * Add a layout template with optional name
 * @param template - Layout template configuration or file path
 * @param name - Optional layout name
 */
function addLayout(template: NuxtTemplate | string, name?: string): void;

Usage Examples:

import { addLayout } from "@nuxt/kit";

// Add layout from file
addLayout("~/layouts/custom.vue", "custom");

// Add layout with template
addLayout({
  src: "~/templates/admin-layout.vue",
  filename: "layouts/admin.vue"
}, "admin");

// Module adding layouts
export default defineNuxtModule({
  setup(options, nuxt) {
    const resolver = createResolver(import.meta.url);
    
    // Add module layouts
    addLayout(resolver.resolve("./runtime/layouts/dashboard.vue"), "dashboard");
    addLayout(resolver.resolve("./runtime/layouts/minimal.vue"), "minimal");
  }
});

Pages & Routing Utilities

Extend pages configuration and route rules.

/**
 * Add route middleware
 * @param input - Middleware configuration or array
 * @param options - Middleware options
 */
function addRouteMiddleware(
  input: NuxtMiddleware | NuxtMiddleware[],
  options?: AddRouteMiddlewareOptions
): void;

/**
 * Extend pages configuration
 * @param cb - Callback to modify pages array
 */
function extendPages(cb: NuxtHooks['pages:extend']): void;

/**
 * Extend route rules configuration
 * @param route - Route pattern
 * @param rule - Route rule configuration
 * @param options - Extension options
 */
function extendRouteRules(
  route: string,
  rule: NitroRouteConfig,
  options?: ExtendRouteRulesOptions
): void;

interface NuxtMiddleware {
  /** Middleware name */
  name: string;
  /** Middleware file path */
  path: string;
  /** Global middleware flag */
  global?: boolean;
}

interface AddRouteMiddlewareOptions {
  /** Override existing middleware */
  override?: boolean;
}

interface ExtendRouteRulesOptions {
  /** Override existing rules */
  override?: boolean;
}

Usage Examples:

import { 
  addRouteMiddleware, 
  extendPages, 
  extendRouteRules 
} from "@nuxt/kit";

// Add route middleware
addRouteMiddleware({
  name: "auth",
  path: "~/middleware/auth.ts",
  global: false
});

// Add global middleware
addRouteMiddleware({
  name: "analytics",
  path: "~/middleware/analytics.global.ts",
  global: true
});

// Extend pages
extendPages((pages) => {
  // Add custom page
  pages.push({
    name: "custom-admin",
    path: "/admin/custom",
    file: "~/pages/admin/custom.vue"
  });
  
  // Modify existing pages
  pages.forEach(page => {
    if (page.path.startsWith("/admin")) {
      page.meta = page.meta || {};
      page.meta.requiresAuth = true;
    }
  });
});

// Extend route rules
extendRouteRules("/api/**", {
  cors: true,
  headers: {
    "Access-Control-Allow-Origin": "*"
  }
});

extendRouteRules("/admin/**", {
  ssr: false,
  prerender: false
});

Advanced Development Patterns

Module with Development Mode Features:

import { useLogger, isIgnored } from "@nuxt/kit";

export default defineNuxtModule({
  setup(options, nuxt) {
    const logger = useLogger("dev-module");
    
    if (nuxt.options.dev) {
      logger.info("Development mode features enabled");
      
      // Add development-only components
      addComponentsDir({
        path: "~/components/dev",
        global: true,
        watch: true
      });
      
      // Add hot-reload support
      nuxt.hook("builder:watch", (event, path) => {
        if (!isIgnored(path) && path.includes("custom-config")) {
          logger.info(`Reloading due to change in: ${path}`);
          // Trigger reload
        }
      });
    }
  }
});

Layer-Aware Component Processing:

import { getLayerDirectories, addComponentsDir, useLogger } from "@nuxt/kit";

export default defineNuxtModule({
  setup() {
    const logger = useLogger("layer-components");
    const layers = getLayerDirectories();
    
    // Process each layer with priority
    layers.forEach((layer, index) => {
      const priority = layers.length - index;
      
      logger.info(`Processing layer ${index} (priority: ${priority})`);
      
      // Add themed components if theme directory exists
      const themeDir = join(layer.app, "components", "theme");
      if (existsSync(themeDir)) {
        addComponentsDir({
          path: themeDir,
          prefix: "Theme",
          priority,
          global: true
        });
      }
    });
  }
});

Types

interface NuxtHooks {
  'pages:extend': (pages: NuxtPage[]) => void;
  'builder:watch': (event: string, path: string) => void;
  [key: string]: (...args: any[]) => any;
}

interface NuxtPage {
  /** Page name */
  name?: string;
  /** Page path */
  path: string;
  /** Page file */
  file?: string;
  /** Page metadata */
  meta?: Record<string, any>;
  /** Child pages */
  children?: NuxtPage[];
}

interface NitroRouteConfig {
  /** Server-side rendering */
  ssr?: boolean;
  /** Prerendering */
  prerender?: boolean;
  /** CORS configuration */
  cors?: boolean;
  /** Response headers */
  headers?: Record<string, string>;
  /** Route priority */
  priority?: number;
  [key: string]: any;
}

Install with Tessl CLI

npx tessl i tessl/npm-nuxt--kit

docs

auto-imports.md

build-system.md

compatibility.md

components.md

configuration.md

context-runtime.md

development-tools.md

index.md

module-system.md

path-resolution.md

plugins-templates.md

server-integration.md

tile.json