Programmatic Usage

Source
Nuxt Kit provides a set of utilities to help you work with Nuxt programmatically. These functions allow you to load Nuxt, build Nuxt, and load Nuxt configuration.

Programmatic usage can be helpful when you want to use Nuxt programmatically, for example, when building a CLI tool or test utils.

loadNuxt

Load Nuxt programmatically. It will load the Nuxt configuration, instantiate and return the promise with Nuxt instance.

Type

function loadNuxt (loadOptions?: LoadNuxtOptions): Promise<Nuxt>

Parameters

loadOptions: Loading conditions for Nuxt. loadNuxt uses c12 under the hood, so it accepts the same options as c12.loadConfig with some additional options:

PropertyTypeRequiredDescription
devbooleanfalseIf set to true, Nuxt will be loaded in development mode.
readybooleantrueIf set to true, Nuxt will be ready to use after the loadNuxt call. If set to false, you will need to call nuxt.ready() to make sure Nuxt is ready to use.

buildNuxt

Build Nuxt programmatically. It will invoke the builder (currently @nuxt/vite-builder or @nuxt/webpack-builder) to bundle the application.

Type

function buildNuxt (nuxt: Nuxt): Promise<any>

Parameters

nuxt: Nuxt instance to build. It can be retrieved from the context via useNuxt() call.

loadNuxtConfig

Load Nuxt configuration. It will return the promise with the configuration object.

Type

function loadNuxtConfig (options: LoadNuxtConfigOptions): Promise<NuxtOptions>

Parameters

options: Options controlling how configuration is located, merged and loaded.

PropertyTypeDefaultDescription
cwdstringprocess.cwd()Directory to load nuxt.config from.
configFilestring'nuxt.config'Name of the config file to load, without an extension.
rcFilestring | false'.nuxtrc'Name of the .rc file to load alongside the config file, or false to load none.
globalRcbooleantrueAlso load the user-level and workspace-level .nuxtrc files.
overridesNuxtConfigundefinedConfiguration applied above every layer, including the root project's own nuxt.config.
defaultsNuxtConfigundefinedConfiguration applied below every layer, before schema defaults.
dotenvboolean | NuxtDotenvOptionstrueLoad .env files into process.env before resolving configuration. Set to false when the environment has already been populated.
envNamestring | falseundefinedEnvironment name used to select $env.* configuration overrides. Takes precedence over envName set in nuxt.config.
resolve(source, context) => ResolvedNuxtLayer | nullishundefinedResolve an extends entry to a layer yourself. Return a nullish value to fall back to the default resolution for that source.
import(id: string) => Promise<unknown>undefinedImport config files with a custom loader rather than the default one, for example to load TypeScript config without Nuxt reaching for jiti.
onConfigResolved(context: ResolvedNuxtConfigContext) => voidundefinedCalled once, and awaited, after configuration has loaded successfully. Not called if loading throws.

onConfigResolved

The context passed to onConfigResolved describes what was loaded:

PropertyTypeDescription
rawConfigNuxtConfigUser configuration merged across all layers, with no schema defaults applied and with overrides, defaults and defaultConfig excluded, so repeated loads of an unchanged project produce an unchanged snapshot.
layersNuxtConfigLayer[]Resolved config layers, highest priority first.
configFilestring?Absolute path of the root nuxt.config file, if one was found.
cwdstringDirectory the configuration was loaded from.

diffNuxtConfig

Compare two rawConfig snapshots (as provided to onConfigResolved) and return the differences between them. This is useful when you watch config files yourself and need to know which keys changed before deciding whether to restart.

Type

function diffNuxtConfig (oldConfig: NuxtConfig, newConfig: NuxtConfig): NuxtConfigDiffEntry[]

Parameters

oldConfig: The previous rawConfig snapshot.

newConfig: The current rawConfig snapshot.

Return Value

An array of entries, one per difference. Each entry has:

PropertyTypeDescription
type'added' | 'removed' | 'changed'How the value changed.
pathArray<string | number>Property path of the changed value, with array indices as numbers, such as ['runtimeConfig', 'public', 'foo']. Prefer this when reading the value back out of a config object.
labelstringpath written as a property accessor, for display or for matching against a known key, such as runtimeConfig.public.foo or modules[0].
newValueunknownPresent for added and changed entries.
oldValueunknownPresent for removed and changed entries.

Functions whose source is unchanged are not reported as changes, so a config that declares inline functions does not diff against itself on every load.

Example

import { diffNuxtConfig, loadNuxtConfig } from '@nuxt/kit'

let previous

async function load () {
  await loadNuxtConfig({
    cwd: process.cwd(),
    onConfigResolved ({ rawConfig }) {
      if (previous) {
        for (const entry of diffNuxtConfig(previous, rawConfig)) {
          console.log(`${entry.label} was ${entry.type}`)
        }
      }
      previous = rawConfig
    },
  })
}

writeTypes

Generates tsconfig.json and writes it to the project buildDir.

Type

function writeTypes (nuxt?: Nuxt): void

Parameters

nuxt: Nuxt instance to build. It can be retrieved from the context via useNuxt() call.