Nuxt3 中文课程 《实战全栈开发简书》.

Nuxt 配置

发现你可以在你的 nuxt.config.ts 文件中使用的所有选项。

这个文件是从 Nuxt 源代码自动生成的。

alias

You can improve your DX by defining additional aliases to access custom directories within your JavaScript and CSS.

  • Type: object
  • Default
{
  "~": "/<srcDir>",
  "@": "/<srcDir>",
  "~~": "/<rootDir>",
  "@@": "/<rootDir>",
  "assets": "/<srcDir>/assets",
  "public": "/<srcDir>/public"
}
Note: Within a webpack context (image sources, CSS - but not JavaScript) you must access your alias by prefixing it with ~.
Note: These aliases will be automatically added to the generated .nuxt/tsconfig.json so you can get full type support and path auto-complete. In case you need to extend options provided by ./.nuxt/tsconfig.json further, make sure to add them here or within the typescript.tsConfig property in nuxt.config.

Example:

export default {
  alias: {
    'images': fileURLToPath(new URL('./assets/images', import.meta.url)),
    'style': fileURLToPath(new URL('./assets/style', import.meta.url)),
    'data': fileURLToPath(new URL('./assets/other/data', import.meta.url))
  }
}

analyzeDir

The directory where Nuxt will store the generated files when running nuxt analyze.

If a relative path is specified, it will be relative to your rootDir.

  • Type: string
  • Default: "/<rootDir>/.nuxt/analyze"

app

Nuxt App configuration.

baseURL

The base path of your Nuxt application.

This can be set at runtime by setting the NUXT_APP_BASE_URL environment variable.

  • Type: string
  • Default: "/"

Example:

NUXT_APP_BASE_URL=/prefix/ node .output/server/index.mjs

buildAssetsDir

The folder name for the built site assets, relative to baseURL (or cdnURL if set). This is set at build time and should not be customized at runtime.

  • Type: string
  • Default: "/_nuxt/"

cdnURL

An absolute URL to serve the public folder from (production-only).

This can be set to a different value at runtime by setting the NUXT_APP_CDN_URL environment variable.

  • Type: string
  • Default: ""

Example:

NUXT_APP_CDN_URL=https://mycdn.org/ node .output/server/index.mjs

Set default configuration for <head> on every page.

  • Type: object
  • Default
{
  "meta": [
    {
      "name": "viewport",
      "content": "width=device-width, initial-scale=1"
    },
    {
      "charset": "utf-8"
    }
  ],
  "link": [],
  "style": [],
  "script": [],
  "noscript": []
}

Example:

app: {
  head: {
    meta: [
      // <meta name="viewport" content="width=device-width, initial-scale=1">
      { name: 'viewport', content: 'width=device-width, initial-scale=1' }
    ],
    script: [
      // <script src="https://myawesome-lib.js"></script>
      { src: 'https://awesome-lib.js' }
    ],
    link: [
      // <link rel="stylesheet" href="https://myawesome-lib.css">
      { rel: 'stylesheet', href: 'https://awesome-lib.css' }
    ],
    // please note that this is an area that is likely to change
    style: [
      // <style type="text/css">:root { color: red }</style>
      { children: ':root { color: red }', type: 'text/css' }
    ],
    noscript: [
      // <noscript>JavaScript is required</noscript>
      { children: 'JavaScript is required' }
    ]
  }
}

keepalive

Default values for KeepAlive configuration between pages.

This can be overridden with definePageMeta on an individual page. Only JSON-serializable values are allowed.

  • Type: boolean
  • Default: false

See: https://vuejs.org/api/built-in-components.html#keepalive

layoutTransition

Default values for layout transitions.

This can be overridden with definePageMeta on an individual page. Only JSON-serializable values are allowed.

  • Type: boolean
  • Default: false

See: https://vuejs.org/api/built-in-components.html#transition

pageTransition

Default values for page transitions.

This can be overridden with definePageMeta on an individual page. Only JSON-serializable values are allowed.

  • Type: boolean
  • Default: false

See: https://vuejs.org/api/built-in-components.html#transition

rootId

Customize Nuxt root element id.

  • Type: string
  • Default: "__nuxt"

rootTag

Customize Nuxt root element tag.

  • Type: string
  • Default: "div"

teleportId

Customize Nuxt Teleport element id.

  • Type: string
  • Default: "teleports"

teleportTag

Customize Nuxt root element tag.

  • Type: string
  • Default: "div"

viewTransition

Default values for view transitions.

This only has an effect when experimental support for View Transitions is enabled in your nuxt.config file. This can be overridden with definePageMeta on an individual page.

  • Type: boolean
  • Default: false

See: https://nuxt.com/docs/getting-started/transitions#view-transitions-api-experimental

appConfig

Additional app configuration

For programmatic usage and type support, you can directly provide app config with this option. It will be merged with app.config file as default value.

nuxt

build

Shared build configuration.

analyze

Nuxt allows visualizing your bundles and how to optimize them.

Set to true to enable bundle analysis, or pass an object with options: for webpack or for vite.

  • Type: object
  • Default
{
  "template": "treemap",
  "projectRoot": "/<rootDir>",
  "filename": "/<rootDir>/.nuxt/analyze/{name}.html"
}

Example:

analyze: {
  analyzerMode: 'static'
}

templates

You can provide your own templates which will be rendered based on Nuxt configuration. This feature is specially useful for using with modules.

Templates are rendered using lodash/template.

  • Type: array

Example:

templates: [
  {
    src: '~/modules/support/plugin.js', // `src` can be absolute or relative
    dst: 'support.js', // `dst` is relative to project `.nuxt` dir
    options: {
      // Options are provided to template as `options` key
      live_chat: false
    }
  }
]

transpile

If you want to transpile specific dependencies with Babel, you can add them here. Each item in transpile can be a package name, a function, a string or regex object matching the dependency's file name.

You can also use a function to conditionally transpile. The function will receive an object ({ isDev, isServer, isClient, isModern, isLegacy }).

  • Type: array

Example:

     transpile: [({ isLegacy }) => isLegacy && 'ky']

buildDir

Define the directory where your built Nuxt files will be placed.

Many tools assume that .nuxt is a hidden directory (because it starts with a .). If that is a problem, you can use this option to prevent that.

  • Type: string
  • Default: "/<rootDir>/.nuxt"

Example:

export default {
  buildDir: 'nuxt-build'
}

builder

The builder to use for bundling the Vue part of your application.

  • Type: string
  • Default: "@nuxt/vite-builder"

components

Configure Nuxt component auto-registration.

Any components in the directories configured here can be used throughout your pages, layouts (and other components) without needing to explicitly import them.

  • Type: object
  • Default
{
  "dirs": [
    {
      "path": "~/components/global",
      "global": true
    },
    "~/components"
  ]
}

See: https://nuxt.com/docs/guide/directory-structure/components

css

You can define the CSS files/modules/libraries you want to set globally (included in every page).

Nuxt will automatically guess the file type by its extension and use the appropriate pre-processor. You will still need to install the required loader if you need to use them.

  • Type: array

Example:

css: [
  // Load a Node.js module directly (here it's a Sass file).
  'bulma',
  // CSS file in the project
  '~/assets/css/main.css',
  // SCSS file in the project
  '~/assets/css/main.scss'
]

debug

Set to true to enable debug mode.

At the moment, it prints out hook names and timings on the server, and logs hook arguments as well in the browser.

  • Type: boolean
  • Default: false

dev

Whether Nuxt is running in development mode.

Normally, you should not need to set this.

  • Type: boolean
  • Default: false

devServer

host

Dev server listening host

https

Whether to enable HTTPS.

  • Type: boolean
  • Default: false

Example:

export default defineNuxtConfig({
  devServer: {
    https: {
      key: './server.key',
      cert: './server.crt'
    }
  }
})

loadingTemplate

Template to show a loading screen

  • Type: function

port

Dev server listening port

  • Type: number
  • Default: 3000

url

Listening dev server URL.

This should not be set directly as it will always be overridden by the dev server with the full URL (for module and internal use).

  • Type: string
  • Default: "http://localhost:3000"

devServerHandlers

Nitro development-only server handlers.

  • Type: array

See: https://nitro.unjs.io/guide/routing

devtools

Enable Nuxt DevTools for development.

Breaking changes for devtools might not reflect on the version of Nuxt.

See: Nuxt DevTools for more information.

dir

Customize default directory structure used by Nuxt.

It is better to stick with defaults unless needed.

assets

The assets directory (aliased as ~assets in your build).

  • Type: string
  • Default: "assets"

layouts

The layouts directory, each file of which will be auto-registered as a Nuxt layout.

  • Type: string
  • Default: "layouts"

middleware

The middleware directory, each file of which will be auto-registered as a Nuxt middleware.

  • Type: string
  • Default: "middleware"

modules

The modules directory, each file in which will be auto-registered as a Nuxt module.

  • Type: string
  • Default: "modules"

pages

The directory which will be processed to auto-generate your application page routes.

  • Type: string
  • Default: "pages"

plugins

The plugins directory, each file of which will be auto-registered as a Nuxt plugin.

  • Type: string
  • Default: "plugins"

public

The directory containing your static files, which will be directly accessible via the Nuxt server and copied across into your dist folder when your app is generated.

  • Type: string
  • Default: "public"

static

  • Type: string
  • Default: "public"

experimental

appManifest

Use app manifests to respect route rules on client-side.

  • Type: boolean
  • Default: true

asyncContext

Enable native async context to be accessible for nested composables

  • Type: boolean
  • Default: false

See: Nuxt PR #20918

asyncEntry

Set to true to generate an async entry point for the Vue bundle (for module federation support).

  • Type: boolean
  • Default: false

clientFallback

Whether to enable the experimental <NuxtClientFallback> component for rendering content on the client if there's an error in SSR.

  • Type: boolean
  • Default: false

clientNodeCompat

Automatically polyfill Node.js imports in the client build using unenv.

  • Type: boolean
  • Default: false

See: https://github.com/unjs/unenv

componentIslands

Experimental component islands support with <NuxtIsland> and .island.vue files.

By default it is set to 'auto', which means it will be enabled only when there are islands, server components or server pages in your app.

  • Type: string
  • Default: "auto"

configSchema

Config schema support

  • Type: boolean
  • Default: true

See: Nuxt Issue #15592

cookieStore

Enables CookieStore support to listen for cookie updates (if supported by the browser) and refresh useCookie ref values.

  • Type: boolean
  • Default: false

See: CookieStore

crossOriginPrefetch

Enable cross-origin prefetch using the Speculation Rules API.

  • Type: boolean
  • Default: false

defaults

This allows specifying the default options for core Nuxt components and composables.

These options will likely be moved elsewhere in the future, such as into app.config or into the app/ directory.

componentName
  • Type: string
  • Default: "NuxtLink"

useAsyncData

Options that apply to useAsyncData (and also therefore useFetch)

deep
  • Type: boolean
  • Default: true

useFetch

emitRouteChunkError

Emit app:chunkError hook when there is an error loading vite/webpack chunks.

By default, Nuxt will also perform a hard reload of the new route when a chunk fails to load when navigating to a new route. You can disable automatic handling by setting this to false, or handle chunk errors manually by setting it to manual.

  • Type: string
  • Default: "automatic"

See: Nuxt PR #19038

externalVue

Externalize vue, @vue/* and vue-router when building.

  • Type: boolean
  • Default: true

See: Nuxt Issue #13632

headNext

Use new experimental head optimisations: - Add the capo.js head plugin in order to render tags in of the head in a more performant way. - Uses the hash hydration plugin to reduce initial hydration

  • Type: boolean
  • Default: false

See: [Nuxt Discussion #22632](https://github.com/nuxt/nuxt/discussions/22632]

inlineRouteRules

Allow defining routeRules directly within your ~/pages directory using defineRouteRules.

Rules are converted (based on the path) and applied for server requests. For example, a rule defined in ~/pages/foo/bar.vue will be applied to /foo/bar requests. A rule in ~/pages/foo/[id].vue will be applied to /foo/** requests. For more control, such as if you are using a custom path or alias set in the page's definePageMeta, you should set routeRules directly within your nuxt.config.

  • Type: boolean
  • Default: false

localLayerAliases

Resolve ~, ~~, @ and @@ aliases located within layers with respect to their layer source and root directories.

  • Type: boolean
  • Default: true

noVueServer

Disable vue server renderer endpoint within nitro.

  • Type: boolean
  • Default: false

payloadExtraction

When this option is enabled (by default) payload of pages that are prerendered are extracted

  • Type: boolean
  • Default: true

polyfillVueUseHead

Whether or not to add a compatibility layer for modules, plugins or user code relying on the old @vueuse/head API.

This can be disabled for most Nuxt sites to reduce the client-side bundle by ~0.5kb.

  • Type: boolean
  • Default: false

renderJsonPayloads

Render JSON payloads with support for revivifying complex types.

  • Type: boolean
  • Default: true

respectNoSSRHeader

Allow disabling Nuxt SSR responses by setting the x-nuxt-no-ssr header.

  • Type: boolean
  • Default: false

restoreState

Whether to restore Nuxt app state from sessionStorage when reloading the page after a chunk error or manual reloadNuxtApp() call.

To avoid hydration errors, it will be applied only after the Vue app has been mounted, meaning there may be a flicker on initial load. Consider carefully before enabling this as it can cause unexpected behavior, and consider providing explicit keys to useState as auto-generated keys may not match across builds.

  • Type: boolean
  • Default: false

scanPageMeta

Allow exposing some route metadata defined in definePageMeta at build-time to modules (alias, name, path, redirect).

This only works with static or strings/arrays rather than variables or conditional assignment. https://github.com/nuxt/nuxt/issues/24770

  • Type: boolean
  • Default: false

sharedPrerenderData

Automatically share payload data between pages that are prerendered. This can result in a significant performance improvement when prerendering sites that use useAsyncData or useFetch and fetch the same data in different pages.

It is particularly important when enabling this feature to make sure that any unique key of your data is always resolvable to the same data. For example, if you are using useAsyncData to fetch data related to a particular page, you should provide a key that uniquely matches that data. (useFetch should do this automatically for you.)

  • Type: boolean
  • Default: false

Example:

// This would be unsafe in a dynamic page (e.g. `[slug].vue`) because the route slug makes a difference
// to the data fetched, but Nuxt can't know that because it's not reflected in the key.
const route = useRoute()
const { data } = await useAsyncData(async () => {
  return await $fetch(`/api/my-page/${route.params.slug}`)
})
// Instead, you should use a key that uniquely identifies the data fetched.
const { data } = await useAsyncData(route.params.slug, async () => {
  return await $fetch(`/api/my-page/${route.params.slug}`)
})

templateRouteInjection

By default the route object returned by the auto-imported useRoute() composable is kept in sync with the current page in view in <NuxtPage>. This is not true for vue-router's exported useRoute or for the default $route object available in your Vue templates.

By enabling this option a mixin will be injected to keep the $route template object in sync with Nuxt's managed useRoute().

  • Type: boolean
  • Default: true

treeshakeClientOnly

Tree shakes contents of client-only components from server bundle.

  • Type: boolean
  • Default: true

See: Nuxt PR #5750

typedPages

Enable the new experimental typed router using unplugin-vue-router.

  • Type: boolean
  • Default: false

viewTransition

Enable View Transition API integration with client-side router.

  • Type: boolean
  • Default: false

See: View Transitions API

watcher

Set an alternative watcher that will be used as the watching service for Nuxt.

Nuxt uses 'chokidar-granular' by default, which will ignore top-level directories (like node_modules and .git) that are excluded from watching. You can set this instead to parcel to use @parcel/watcher, which may improve performance in large projects or on Windows platforms. You can also set this to chokidar to watch all files in your source directory.

  • Type: string
  • Default: "chokidar-granular"

See: chokidarSee: Parcel watcher

writeEarlyHints

Write early hints when using node server.

  • Type: boolean
  • Default: false
Note: nginx does not support 103 Early hints in the current version.

extends

Extend project from multiple local or remote sources.

Value should be either a string or array of strings pointing to source directories or config path relative to current config. You can use github:, gh: gitlab: or bitbucket:.

  • Default: null

See: https://github.com/unjs/c12#extending-config-layer-from-remote-sourcesSee: https://github.com/unjs/giget

extensions

The extensions that should be resolved by the Nuxt resolver.

  • Type: array
  • Default
[
  ".js",
  ".jsx",
  ".mjs",
  ".ts",
  ".tsx",
  ".vue"
]

features

Some features of Nuxt are available on an opt-in basis, or can be disabled based on your needs.

devLogs

Stream server logs to the client as you are developing. These logs can be handled in the dev:ssr-logs hook.

If set to silent, the logs will not be printed to the browser console.

  • Type: boolean
  • Default: false

inlineStyles

Inline styles when rendering HTML (currently vite only).

You can also pass a function that receives the path of a Vue component and returns a boolean indicating whether to inline the styles for that component.

  • Type: boolean
  • Default: true

noScripts

Turn off rendering of Nuxt scripts and JS resource hints. You can also disable scripts more granularly within routeRules.

  • Type: boolean
  • Default: false

future

future is for early opting-in to new features that will become default in a future (possibly major) version of the framework.

typescriptBundlerResolution

This enables 'Bundler' module resolution mode for TypeScript, which is the recommended setting for frameworks like Nuxt and Vite.

It improves type support when using modern libraries with exports. You can set it to false to use the legacy 'Node' mode, which is the default for TypeScript. See https://github.com/microsoft/TypeScript/pull/51669

  • Type: boolean
  • Default: true

generate

exclude

This option is no longer used. Instead, use nitro.prerender.ignore.

  • Type: array

routes

The routes to generate.

If you are using the crawler, this will be only the starting point for route generation. This is often necessary when using dynamic routes. It is preferred to use nitro.prerender.routes.

  • Type: array

Example:

routes: ['/users/1', '/users/2', '/users/3']

hooks

Hooks are listeners to Nuxt events that are typically used in modules, but are also available in nuxt.config.

Internally, hooks follow a naming pattern using colons (e.g., build:done). For ease of configuration, you can also structure them as an hierarchical object in nuxt.config (as below).

  • Default: null

Example:

import fs from 'node:fs'
import path from 'node:path'
export default {
  hooks: {
    build: {
      done(builder) {
        const extraFilePath = path.join(
          builder.nuxt.options.buildDir,
          'extra-file'
        )
        fs.writeFileSync(extraFilePath, 'Something extra')
      }
    }
  }
}

ignore

More customizable than ignorePrefix: all files matching glob patterns specified inside the ignore array will be ignored in building.

  • Type: array
  • Default
[
  "**/*.stories.{js,cts,mts,ts,jsx,tsx}",
  "**/*.{spec,test}.{js,cts,mts,ts,jsx,tsx}",
  "**/*.d.{cts,mts,ts}",
  "**/.{pnpm-store,vercel,netlify,output,git,cache,data}",
  ".nuxt/analyze",
  ".nuxt",
  "**/-*.*"
]

ignoreOptions

Pass options directly to node-ignore (which is used by Nuxt to ignore files).

See: node-ignoreExample:

ignoreOptions: {
  ignorecase: false
}

ignorePrefix

Any file in pages/, layouts/, middleware/ or store/ will be ignored during building if its filename starts with the prefix specified by ignorePrefix.

  • Type: string
  • Default: "-"

imports

Configure how Nuxt auto-imports composables into your application.

See: Nuxt 3 documentation

dirs

An array of custom directories that will be auto-imported. Note that this option will not override the default directories (~/composables, ~/utils).

  • Type: array

Example:

imports: {
  // Auto-import pinia stores defined in `~/stores`
  dirs: ['stores']
}