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

path-resolution.mddocs/

Path Resolution & File Utilities

Path resolution, alias handling, and file discovery with Nuxt-aware logic. Provides utilities for resolving paths, finding files, and handling aliases within the Nuxt ecosystem.

Capabilities

Path Resolution

Resolve paths with Nuxt-aware alias support and extension handling.

/**
 * Resolve full path respecting Nuxt aliases and extensions
 * @param path - Path to resolve
 * @param opts - Resolution options
 * @returns Promise resolving to full resolved path
 */
function resolvePath(path: string, opts?: ResolvePathOptions): Promise<string>;

/**
 * Resolve path aliases
 * @param path - Path with potential aliases
 * @param alias - Alias mapping object
 * @returns Resolved path string
 */
function resolveAlias(
  path: string,
  alias?: Record<string, string>
): string;

interface ResolvePathOptions {
  /** Current working directory */
  cwd?: string;
  /** File extensions to try */
  extensions?: string[];
  /** Alias mappings */
  alias?: Record<string, string>;
  /** Resolve as URL */
  url?: boolean;
}

Usage Examples:

import { resolvePath, resolveAlias } from "@nuxt/kit";

// Resolve with Nuxt aliases
const componentPath = await resolvePath("~/components/MyComponent.vue");
// Returns: /path/to/project/components/MyComponent.vue

const utilPath = await resolvePath("@/utils/helpers");
// Returns: /path/to/project/utils/helpers.ts (with extension resolution)

// Custom alias resolution
const aliasedPath = resolveAlias("@custom/module", {
  "@custom": "/path/to/custom"
});
// Returns: /path/to/custom/module

// Advanced path resolution
const resolvedPath = await resolvePath("~/composables/useAuth", {
  extensions: [".ts", ".js", ".mjs"],
  cwd: "/custom/working/dir"
});

File Discovery

Find and resolve files with pattern matching and ignore pattern support.

/**
 * Find first existing file in paths
 * @param paths - Path or array of paths to check
 * @param opts - Path resolution options
 * @param pathType - Type of path to resolve
 * @returns Promise resolving to first found path or null
 */
function findPath(
  paths: string | string[],
  opts?: ResolvePathOptions,
  pathType?: PathType
): Promise<string | null>;

/**
 * Resolve files in directory matching pattern, respecting .nuxtignore
 * @param path - Directory path to scan
 * @param pattern - Glob pattern(s) to match
 * @param opts - File resolution options
 * @returns Promise resolving to array of matching file paths
 */
function resolveFiles(
  path: string,
  pattern: string | string[],
  opts?: any
): Promise<string[]>;

type PathType = "file" | "dir";

Usage Examples:

import { findPath, resolveFiles } from "@nuxt/kit";

// Find first existing config file
const configPath = await findPath([
  "nuxt.config.ts",
  "nuxt.config.js",
  "nuxt.config.mjs"
]);

// Find component file
const component = await findPath("~/components/MyComponent", {
  extensions: [".vue", ".ts", ".js"]
});

// Resolve all Vue components in directory
const components = await resolveFiles(
  "~/components",
  "**/*.vue"
);

// Resolve with multiple patterns
const sourceFiles = await resolveFiles(
  "~/src",
  ["**/*.ts", "**/*.js", "!**/*.test.*"]
);

// Resolve TypeScript files only
const tsFiles = await resolveFiles(
  "~/utils",
  "**/*.ts",
  { ignore: ["**/*.d.ts"] }
);

Resolver Creation

Create reusable path resolvers for consistent path resolution within modules.

/**
 * Create a relative resolver for paths
 * @param base - Base path or URL for relative resolution
 * @returns Resolver object with resolve methods
 */
function createResolver(base: string | URL): Resolver;

interface Resolver {
  /** Resolve path relative to base */
  resolve(...paths: string[]): string;
  /** Resolve path relative to base and ensure it exists */
  resolvePath(path: string, opts?: ResolvePathOptions): Promise<string>;
}

Usage Examples:

import { createResolver } from "@nuxt/kit";
import { fileURLToPath } from "node:url";

// Create resolver from import.meta.url
const resolver = createResolver(import.meta.url);

// Resolve relative to current file
const templatePath = resolver.resolve("./templates/component.vue");
const configPath = resolver.resolve("../config/default.json");

// Module resolver pattern
export default defineNuxtModule({
  setup(options, nuxt) {
    const resolver = createResolver(import.meta.url);
    
    // Resolve runtime directory
    const runtimeDir = resolver.resolve("./runtime");
    
    // Add plugin from resolved path
    addPlugin({
      src: resolver.resolve("./runtime/plugin.mjs"),
      mode: "all"
    });
    
    // Add template with resolved source
    addTemplate({
      src: resolver.resolve("./templates/config.mjs"),
      filename: "my-module-config.mjs"
    });
  }
});

// Resolver with path validation
const resolver = createResolver(import.meta.url);

async function loadTemplate(name: string) {
  const templatePath = await resolver.resolvePath(`./templates/${name}`, {
    extensions: [".vue", ".ts", ".js"]
  });
  return templatePath;
}

Module Resolution

Specialized utilities for resolving Nuxt modules and dependencies.

/**
 * Resolve Nuxt module paths
 * @param base - Base directory for resolution
 * @param paths - Module paths to resolve
 * @returns Promise resolving to array of resolved module paths
 */
function resolveNuxtModule(base: string, paths: string[]): Promise<string[]>;

/**
 * Try to resolve a module from given URLs/paths
 * @param id - Module identifier to resolve
 * @param url - URL or array of URLs to resolve from
 * @returns Promise resolving to resolved path or undefined if not found
 */
function tryResolveModule(id: string, url: URL | URL[]): Promise<string | undefined>;
function tryResolveModule(id: string, url: string | string[]): Promise<string | undefined>;

/**
 * Resolve a module using standard Node.js resolution
 * @param id - Module identifier to resolve
 * @param options - Resolution options
 * @returns Resolved module path
 */
function resolveModule(id: string, options?: ResolveModuleOptions): string;

/**
 * Import a module dynamically with automatic de-defaulting
 * @param id - Module identifier to import
 * @param opts - Import options
 * @returns Promise resolving to imported module
 */
function importModule<T = unknown>(id: string, opts?: ImportModuleOptions): Promise<T>;

/**
 * Try to import a module, returning undefined if it fails
 * @param id - Module identifier to import
 * @param opts - Import options
 * @returns Promise resolving to imported module or undefined
 */
function tryImportModule<T = unknown>(id: string, opts?: ImportModuleOptions): Promise<T | undefined>;

/**
 * Require a module synchronously (deprecated - use importModule instead)
 * @deprecated Please use `importModule` instead
 * @param id - Module identifier to require
 * @param opts - Import options
 * @returns Required module
 */
function requireModule<T = unknown>(id: string, opts?: ImportModuleOptions): T;

/**
 * Try to require a module synchronously (deprecated - use tryImportModule instead)
 * @deprecated Please use `tryImportModule` instead
 * @param id - Module identifier to require
 * @param opts - Import options
 * @returns Required module or undefined if it fails
 */
function tryRequireModule<T = unknown>(id: string, opts?: ImportModuleOptions): T | undefined;

interface ResolveModuleOptions {
  /** @deprecated use `url` with URLs pointing at a file - never a directory */
  paths?: string | string[];
  url?: URL | URL[];
}

interface ImportModuleOptions extends ResolveModuleOptions {
  /** Automatically de-default the result of requiring the module */
  interopDefault?: boolean;
}

Usage Examples:

import { 
  resolveNuxtModule, 
  importModule, 
  tryImportModule, 
  tryResolveModule, 
  requireModule, 
  tryRequireModule 
} from "@nuxt/kit";

// Resolve module dependencies
const modulePaths = await resolveNuxtModule(process.cwd(), [
  "@nuxtjs/tailwindcss",
  "@pinia/nuxt",
  "nuxt-icon"
]);

console.log("Found modules:", modulePaths);

// Import module dynamically (preferred)
const lodash = await importModule("lodash");
console.log(lodash.camelCase("hello world"));

// Try to import module (returns undefined if fails)
const optionalModule = await tryImportModule("optional-dependency");
if (optionalModule) {
  // Use optional module
}

// Try to resolve module path
const modulePath = await tryResolveModule("my-module", import.meta.url);
if (modulePath) {
  console.log("Module found at:", modulePath);
}

// Deprecated: Use requireModule (shows deprecation warning)
try {
  const config = requireModule("./config.js");
} catch (error) {
  console.error("Failed to require config");
}

// Deprecated: Try to require module
const optionalConfig = tryRequireModule("./optional-config.js");
if (optionalConfig) {
  // Use config
}

Ignore Pattern Integration

Path resolution that respects Nuxt ignore patterns and .nuxtignore files.

/**
 * 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,
  resolveFiles 
} from "@nuxt/kit";

// Check if specific path is ignored
if (isIgnored("node_modules/package")) {
  console.log("Path is ignored");
}

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

const files = ["src/component.vue", "node_modules/lib.js", ".nuxt/dist"];
const validFiles = files.filter(file => !shouldIgnore(file));

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

// Use with file resolution
const sourceFiles = await resolveFiles("~/src", "**/*", {
  ignore: resolveIgnorePatterns()
});

Advanced Path Resolution Patterns

Module-Relative Resolution:

import { createResolver, addComponent, addPlugin } from "@nuxt/kit";

export default defineNuxtModule({
  setup() {
    const resolver = createResolver(import.meta.url);
    
    // Resolve paths relative to module
    const runtimeDir = resolver.resolve("./runtime");
    const componentsDir = resolver.resolve("./components");
    
    // Use resolved paths
    addPlugin(resolver.resolve(runtimeDir, "plugin.mjs"));
    
    addComponent({
      name: "ModuleComponent",
      filePath: resolver.resolve(componentsDir, "Component.vue")
    });
  }
});

Dynamic Path Resolution:

import { resolvePath, findPath } from "@nuxt/kit";

export default defineNuxtModule({
  async setup(options) {
    // Find user's preferred config format
    const configFile = await findPath([
      "my-module.config.ts",
      "my-module.config.js",
      "my-module.config.json"
    ]);
    
    if (configFile) {
      const config = await import(configFile);
      // Use config...
    }
    
    // Resolve theme files
    if (options.theme) {
      const themePath = await resolvePath(`~/themes/${options.theme}`);
      // Load theme...
    }
  }
});

Types

interface FileStats {
  isFile(): boolean;
  isDirectory(): boolean;
  size: number;
  mtime: Date;
  [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