CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-nuxt

Nuxt is a free and open-source framework with an intuitive and extendable way to create type-safe, performant and production-grade full-stack web applications and websites with Vue.js.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

module-dev.mddocs/

Module Development

Comprehensive utilities for developing Nuxt modules, including configuration, plugins, components, and build system integration. The Nuxt Kit provides everything needed to create powerful, reusable modules for the Nuxt ecosystem.

Capabilities

Module Definition

Define and create Nuxt modules with proper typing and lifecycle management.

/**
 * Define a Nuxt module with proper typing and lifecycle management
 * @param definition - Module definition object or setup function
 * @returns Configured Nuxt module
 */
function defineNuxtModule<OptionsT = Record<string, any>>(
  definition: ModuleDefinition<OptionsT> | ModuleSetupFunction<OptionsT>
): NuxtModule<OptionsT>;

interface ModuleDefinition<T = Record<string, any>> {
  /** Module metadata */
  meta?: ModuleMeta;
  /** Default options */
  defaults?: T | ((nuxt: Nuxt) => T);
  /** Module setup function */
  setup?: ModuleSetupFunction<T>;
  /** Module compatibility */
  compatibility?: NuxtCompatibility;
}

interface ModuleMeta {
  /** Module name */
  name?: string;
  /** Module version */
  version?: string;
  /** Module configuration key */
  configKey?: string;
  /** Module compatibility info */
  compatibility?: NuxtCompatibility;
}

type ModuleSetupFunction<T = Record<string, any>> = (
  resolvedOptions: T,
  nuxt: Nuxt
) => void | Promise<void> | ModuleSetupReturn;

interface ModuleSetupReturn {
  /** Timings for performance tracking */
  timings?: {
    setup?: number;
    [key: string]: number | undefined;
  };
}

Usage Examples:

// Basic module definition
export default defineNuxtModule({
  meta: {
    name: "my-module",
    configKey: "myModule"
  },
  defaults: {
    enabled: true,
    apiUrl: "/api"
  },
  setup(options, nuxt) {
    console.log("Setting up my module with options:", options);
  }
});

// Module with TypeScript options
interface MyModuleOptions {
  enabled: boolean;
  apiUrl: string;
  features: {
    auth: boolean;
    analytics: boolean;
  };
}

export default defineNuxtModule<MyModuleOptions>({
  meta: {
    name: "my-typed-module",
    version: "1.0.0",
    configKey: "myTypedModule"
  },
  defaults: {
    enabled: true,
    apiUrl: "/api",
    features: {
      auth: true,
      analytics: false
    }
  },
  setup(options, nuxt) {
    if (!options.enabled) return;
    
    // Module setup logic
    addPlugin(createResolver(import.meta.url).resolve("./runtime/plugin"));
    
    if (options.features.auth) {
      addServerHandler({
        route: "/api/auth/**",
        handler: createResolver(import.meta.url).resolve("./server/auth")
      });
    }
  }
});

// Async module setup
export default defineNuxtModule({
  meta: {
    name: "async-module"
  },
  async setup(options, nuxt) {
    // Async operations
    const packageInfo = await readPackageJSON();
    
    // Add runtime config
    updateRuntimeConfig({
      myModule: {
        version: packageInfo.version
      }
    });
  }
});

Context Management

Access and manage the Nuxt context within modules and utilities.

/**
 * Get the current Nuxt instance
 * @returns Current Nuxt instance
 * @throws Error if called outside Nuxt context
 */
function useNuxt(): Nuxt;

/**
 * Try to get the current Nuxt instance
 * @returns Current Nuxt instance or null if not available
 */
function tryUseNuxt(): Nuxt | null;

/**
 * Get the current Nuxt context
 * @returns Nuxt context
 */
function getNuxtCtx(): NuxtContext;

/**
 * Run a function within Nuxt context
 * @param nuxt - Nuxt instance
 * @param fn - Function to run
 * @returns Result of the function
 */
function runWithNuxtContext<T>(nuxt: Nuxt, fn: () => T): T;

interface Nuxt {
  /** Nuxt options */
  options: NuxtOptions;
  /** Hook system */
  hooks: Hookable<NuxtHooks>;
  /** Module container */
  moduleContainer: ModuleContainer;
  /** Call hook */
  callHook: (name: keyof NuxtHooks, ...args: any[]) => Promise<void>;
  /** Add hook */
  hook: (name: keyof NuxtHooks, fn: Function) => void;
  /** Close Nuxt */
  close: () => Promise<void>;
  [key: string]: any;
}

Usage Examples:

// Using Nuxt context in utilities
function addCustomPlugin() {
  const nuxt = useNuxt();
  
  addPlugin({
    src: createResolver(import.meta.url).resolve("./plugin.js"),
    mode: "client"
  });
}

// Safe context access
function maybeAddPlugin() {
  const nuxt = tryUseNuxt();
  
  if (nuxt) {
    addPlugin("./plugin.js");
  }
}

// Running with context
async function setupModule(nuxt: Nuxt) {
  await runWithNuxtContext(nuxt, () => {
    addPlugin("./plugin.js");
    addComponent({
      name: "MyComponent",
      filePath: "./components/MyComponent.vue"
    });
  });
}

// Hook management
function registerHooks() {
  const nuxt = useNuxt();
  
  nuxt.hook("ready", async () => {
    console.log("Nuxt is ready!");
  });
  
  nuxt.hook("build:before", () => {
    console.log("Build starting...");
  });
}

Plugin Management

Add and manage Nuxt plugins programmatically.

/**
 * Add a plugin to the Nuxt application
 * @param plugin - Plugin options or path
 */
function addPlugin(plugin: AddPluginOptions | string): void;

/**
 * Add a plugin template with processing
 * @param pluginOptions - Plugin template options
 * @returns Added template
 */
function addPluginTemplate(pluginOptions: NuxtPluginTemplate): NuxtTemplate;

/**
 * Normalize plugin options
 * @param plugin - Plugin to normalize
 * @returns Normalized plugin
 */
function normalizePlugin(plugin: NuxtPlugin): NuxtPlugin;

interface AddPluginOptions {
  /** Plugin source path */
  src: string;
  /** Plugin filename */
  fileName?: string;
  /** Plugin mode */
  mode?: "client" | "server" | "all";
  /** Plugin options */
  options?: Record<string, any>;
}

interface NuxtPluginTemplate {
  /** Template source */
  src?: string;
  /** Template filename */
  filename?: string;
  /** Template destination */
  dst?: string;
  /** Template options */
  options?: Record<string, any>;
  /** Template mode */
  mode?: "client" | "server" | "all";
  /** Whether plugin should be SSR-friendly */
  ssr?: boolean;
}

Usage Examples:

// Add simple plugin
addPlugin("~/plugins/my-plugin.client.js");

// Add plugin with options
addPlugin({
  src: createResolver(import.meta.url).resolve("./runtime/plugin.js"),
  mode: "client",
  options: {
    apiKey: "abc123"
  }
});

// Add plugin template
addPluginTemplate({
  src: createResolver(import.meta.url).resolve("./templates/plugin.ejs"),
  filename: "my-plugin.js",
  options: {
    config: moduleOptions
  }
});

// Add multiple plugins
const resolver = createResolver(import.meta.url);

addPlugin(resolver.resolve("./runtime/composables"));
addPlugin({
  src: resolver.resolve("./runtime/auth.client.js"),
  mode: "client"
});
addPlugin({
  src: resolver.resolve("./runtime/server.server.js"),
  mode: "server"
});

Component Management

Register and manage components automatically.

/**
 * Add a component to auto-discovery
 * @param options - Component registration options
 */
function addComponent(options: AddComponentOptions): void;

/**
 * Add component exports for tree-shaking
 * @param exports - Component exports to add
 */
function addComponentExports(exports: ComponentExport[]): void;

/**
 * Add a directory for component auto-discovery
 * @param dir - Directory options
 */
function addComponentsDir(dir: ComponentsDir): void;

interface AddComponentOptions {
  /** Component name */
  name: string;
  /** Component file path */
  filePath: string;
  /** Export name (for named exports) */
  export?: string;
  /** Global registration */
  global?: boolean;
  /** Component prefix */
  prefix?: string;
  /** Component suffix */
  suffix?: string;
  /** Pascal case name */
  pascalName?: string;
  /** Kebab case name */
  kebabName?: string;
  /** Short name */
  shortPath?: string;
  /** Chunk name */
  chunkName?: string;
  /** Component mode */
  mode?: "client" | "server" | "all";
  /** Island component */
  island?: boolean;
}

interface ComponentExport {
  /** Export name */
  name: string;
  /** Export source */
  as?: string;
  /** Export from */
  from: string;
}

interface ComponentsDir {
  /** Directory path */
  path: string;
  /** Directory prefix */
  prefix?: string;
  /** Directory suffix */
  suffix?: string;
  /** Global components */
  global?: boolean;
  /** Watch directory */
  watch?: boolean;
  /** File extensions */
  extensions?: string[];
  /** File patterns */
  pattern?: string | string[];
  /** Ignore patterns */
  ignore?: string[];
  /** Transpile components */
  transpile?: boolean;
  /** Island components */
  island?: boolean;
}

Usage Examples:

// Add single component
addComponent({
  name: "MyButton",
  filePath: createResolver(import.meta.url).resolve("./runtime/components/MyButton.vue"),
  global: true
});

// Add component with custom configuration
addComponent({
  name: "LazyChart",
  filePath: "./components/Chart.vue",
  mode: "client",
  prefix: "Lazy",
  island: true
});

// Add components directory
addComponentsDir({
  path: createResolver(import.meta.url).resolve("./runtime/components"),
  prefix: "My",
  global: true
});

// Add component exports for tree-shaking
addComponentExports([
  { name: "MyButton", from: "./components/MyButton" },
  { name: "MyInput", from: "./components/MyInput" },
  { name: "default", as: "MyCard", from: "./components/MyCard" }
]);

// Conditional component registration
if (moduleOptions.includeUI) {
  addComponentsDir({
    path: resolver.resolve("./runtime/ui"),
    prefix: "UI"
  });
}

Build System Integration

Integrate with Nuxt's build system using Vite, webpack, and other build tools.

/**
 * Add a build plugin
 * @param plugin - Build plugin to add
 */
function addBuildPlugin(plugin: any): void;

/**
 * Add a Vite plugin
 * @param plugin - Vite plugin to add
 */
function addVitePlugin(plugin: any): void;

/**
 * Add a webpack plugin
 * @param plugin - Webpack plugin to add
 */
function addWebpackPlugin(plugin: any): void;

/**
 * Extend Vite configuration
 * @param config - Vite config to merge
 * @param options - Extension options
 */
function extendViteConfig(config: any, options?: ExtendConfigOptions): void;

/**
 * Extend webpack configuration
 * @param config - Webpack config to merge
 * @param options - Extension options
 */
function extendWebpackConfig(config: any, options?: ExtendConfigOptions): void;

interface ExtendConfigOptions {
  /** Development mode only */
  dev?: boolean;
  /** Production mode only */
  build?: boolean;
  /** Server-side only */
  server?: boolean;
  /** Client-side only */
  client?: boolean;
}

Usage Examples:

// Add Vite plugin
import { defineNuxtModule } from '@nuxt/kit';
import MyVitePlugin from 'my-vite-plugin';

export default defineNuxtModule({
  setup() {
    addVitePlugin(MyVitePlugin({
      option1: 'value1'
    }));
  }
});

// Extend Vite config
extendViteConfig({
  define: {
    __MODULE_VERSION__: JSON.stringify(moduleVersion)
  },
  optimizeDeps: {
    include: ['my-dependency']
  }
});

// Add webpack plugin
import MyWebpackPlugin from 'my-webpack-plugin';

addWebpackPlugin(new MyWebpackPlugin({
  option1: 'value1'
}));

// Conditional build configuration
extendViteConfig({
  build: {
    rollupOptions: {
      external: ['external-lib']
    }
  }
}, { build: true }); // Only in production

// Add CSS processing
extendViteConfig({
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@import "~/assets/styles/variables.scss";`
      }
    }
  }
});

Server Integration

Add server handlers, middleware, and API routes.

/**
 * Add a server handler
 * @param handler - Server handler options
 */
function addServerHandler(handler: {
  route?: string;
  handler: string;
  method?: string;
  middleware?: boolean;
}): void;

/**
 * Add development server handler
 * @param handler - Development server handler options
 */
function addDevServerHandler(handler: {
  route?: string;
  handler: string;
  method?: string;
}): void;

/**
 * Add server imports
 * @param imports - Server imports to add
 */
function addServerImports(imports: Import[]): void;

/**
 * Add server imports directory
 * @param dirs - Directory paths or options
 */
function addServerImportsDir(dirs: string | string[]): void;

/**
 * Access Nitro instance
 * @returns Nitro instance
 */
function useNitro(): Nitro;

Usage Examples:

// Add API route
addServerHandler({
  route: "/api/my-module/**",
  handler: createResolver(import.meta.url).resolve("./server/api/handler.js")
});

// Add middleware
addServerHandler({
  handler: createResolver(import.meta.url).resolve("./server/middleware/auth.js"),
  middleware: true
});

// Add development-only handler
addDevServerHandler({
  route: "/api/dev/**",
  handler: createResolver(import.meta.url).resolve("./server/dev-handler.js")
});

// Add server utils
addServerImportsDir(createResolver(import.meta.url).resolve("./server/utils"));

// Add specific server imports
addServerImports([
  { name: "myServerUtil", from: createResolver(import.meta.url).resolve("./server/utils") }
]);

// Access Nitro for advanced configuration
const nitro = useNitro();
nitro.options.runtimeConfig.myModule = moduleOptions;

Module Utilities

Additional utilities for module development.

/**
 * Create a path resolver for the module
 * @param base - Base path (usually import.meta.url)
 * @returns Resolver functions
 */
function createResolver(base: string | URL): Resolver;

/**
 * Update runtime configuration
 * @param config - Configuration to merge
 */
function updateRuntimeConfig(config: Record<string, any>): void;

/**
 * Add template
 * @param template - Template options
 * @returns Added template
 */
function addTemplate(template: NuxtTemplate): NuxtTemplate;

/**
 * Add type template
 * @param template - Type template options
 * @returns Added template
 */
function addTypeTemplate(template: NuxtTemplate): NuxtTemplate;

interface Resolver {
  resolve(...paths: string[]): string;
  resolvePath(path: string): Promise<string>;
}

Usage Examples:

// Module with resolver
export default defineNuxtModule({
  setup() {
    const resolver = createResolver(import.meta.url);
    
    // Resolve paths relative to module
    addPlugin(resolver.resolve("./runtime/plugin.js"));
    addComponent({
      name: "MyComponent",
      filePath: resolver.resolve("./runtime/components/MyComponent.vue")
    });
  }
});

// Update runtime config
updateRuntimeConfig({
  myModule: {
    apiUrl: moduleOptions.apiUrl,
    version: "1.0.0"
  }
});

// Add templates
addTemplate({
  filename: "my-module-config.mjs",
  src: resolver.resolve("./templates/config.ejs"),
  options: {
    ...moduleOptions
  }
});

// Add TypeScript definitions
addTypeTemplate({
  filename: "types/my-module.d.ts",
  src: resolver.resolve("./templates/types.d.ts"),
  options: moduleOptions
});

Complete Module Example

import { defineNuxtModule, createResolver, addPlugin, addComponent, addServerHandler, updateRuntimeConfig } from '@nuxt/kit';

interface ModuleOptions {
  apiUrl: string;
  features: {
    auth: boolean;
    analytics: boolean;
  };
}

export default defineNuxtModule<ModuleOptions>({
  meta: {
    name: "awesome-module",
    version: "1.0.0",
    configKey: "awesomeModule",
    compatibility: {
      nuxt: "^3.0.0"
    }
  },
  defaults: {
    apiUrl: "/api",
    features: {
      auth: true,
      analytics: false
    }
  },
  async setup(options, nuxt) {
    const resolver = createResolver(import.meta.url);

    // Add runtime config
    updateRuntimeConfig({
      awesomeModule: {
        apiUrl: options.apiUrl
      }
    });

    // Add main plugin
    addPlugin({
      src: resolver.resolve("./runtime/plugin.js"),
      options
    });

    // Add components
    addComponent({
      name: "AwesomeButton",
      filePath: resolver.resolve("./runtime/components/AwesomeButton.vue"),
      global: true
    });

    // Conditional features
    if (options.features.auth) {
      addServerHandler({
        route: "/api/auth/**",
        handler: resolver.resolve("./server/auth.js")
      });
      
      addPlugin({
        src: resolver.resolve("./runtime/auth.client.js"),
        mode: "client"
      });
    }

    if (options.features.analytics) {
      addPlugin({
        src: resolver.resolve("./runtime/analytics.js"),
        options: {
          trackingId: options.trackingId
        }
      });
    }

    // Development utilities
    if (nuxt.options.dev) {
      addDevServerHandler({
        route: "/api/awesome-dev/**",
        handler: resolver.resolve("./server/dev.js")
      });
    }

    console.log(`✨ Awesome Module initialized with API URL: ${options.apiUrl}`);
  }
});

Types

interface NuxtCompatibility {
  nuxt?: string;
  bridge?: boolean;
}

interface ModuleContainer {
  addModule(module: any, options?: any): Promise<void>;
  requireModule(module: any, options?: any): Promise<any>;
  addPlugin(template: any): void;
  addLayout(template: any, name?: string): void;
  addServerMiddleware(middleware: any): void;
  extendBuild(fn: Function): void;
  extendRoutes(fn: Function): void;
}

interface NuxtContext {
  nuxt: Nuxt;
  isStatic: boolean;
  isDev: boolean;
  isHMR: boolean;
  app: any;
  payload: any;
}

interface Import {
  name: string;
  as?: string;
  from: string;
}

interface Nitro {
  options: NitroOptions;
  hooks: Hookable;
  [key: string]: any;
}

interface NitroOptions {
  runtimeConfig: Record<string, any>;
  [key: string]: any;
}

Install with Tessl CLI

npx tessl i tessl/npm-nuxt

docs

app-lifecycle.md

configuration.md

core.md

data-fetching.md

head.md

index.md

module-dev.md

navigation.md

performance.md

ssr.md

state.md

tile.json