实验性功能
Nuxt 实验性功能可以在 Nuxt 配置文件中启用。
¥The Nuxt experimental features can be enabled in the Nuxt configuration file.
Nuxt 内部使用 @nuxt/schema
来定义这些实验性功能。你可以参考 API 文档 或 源代码 了解更多信息。
¥Internally, Nuxt uses @nuxt/schema
to define these experimental features. You can refer to the API documentation or the source code for more information.
asyncContext
启用原生异步上下文,以便 Nuxt 和 Nitro 中的嵌套可组合项可以访问。这提供了在异步可组合项中使用可组合项的可能性,并降低了出现 Nuxt instance is unavailable
错误的几率。
¥Enable native async context to be accessible for nested composables in Nuxt and in Nitro. This opens the possibility to use composables inside async composables and reduce the chance to get the Nuxt instance is unavailable
error.
export default defineNuxtConfig({
experimental: {
asyncContext: true
}
})
:
请参阅 GitHub 拉取请求中的完整解释。
¥See full explanation on the GitHub pull-request.
::
asyncEntry
启用为 Vue bundle 生成异步入口点,以辅助模块联合支持。
¥Enables generation of an async entry point for the Vue bundle, aiding module federation support.
export default defineNuxtConfig({
experimental: {
asyncEntry: true
}
})
externalVue
构建时将 vue
、@vue/*
和 vue-router
外部化。
¥Externalizes vue
, @vue/*
and vue-router
when building.
默认启用。
¥Enabled by default.
export default defineNuxtConfig({
experimental: {
externalVue: true
}
})
emitRouteChunkError
当加载 vite/webpack 数据块时出错,会触发 app:chunkError
钩子。默认行为是在区块加载失败时,导航到新路由时重新加载新路由。
¥Emits app:chunkError
hook when there is an error loading vite/webpack chunks. Default behavior is to perform a reload of the new route on navigation to a new route when a chunk fails to load.
如果你将其设置为 'automatic-immediate'
,Nuxt 将立即重新加载当前路由,而不是等待导航。这对于非导航触发的块错误很有用,例如,当你的 Nuxt 应用无法加载 惰性组件 时。此行为的潜在缺点是不必要的重新加载,例如,当你的应用不需要导致错误的块时。
¥If you set this to 'automatic-immediate'
Nuxt will reload the current route immediately, instead of waiting for a navigation. This is useful for chunk errors that are not triggered by navigation, e.g., when your Nuxt app fails to load a lazy component. A potential downside of this behavior is undesired reloads, e.g., when your app does not need the chunk that caused the error.
你可以将其设置为 false
来禁用自动处理,或者将其设置为 manual
来手动处理块错误。
¥You can disable automatic handling by setting this to false
, or handle chunk errors manually by setting it to manual
.
export default defineNuxtConfig({
experimental: {
emitRouteChunkError: 'automatic' // or 'automatic-immediate', 'manual' or false
}
})
restoreState
允许在出现块错误或手动调用 reloadNuxtApp()
后重新加载页面时从 sessionStorage
恢复 Nuxt 应用状态。
¥Allows Nuxt app state to be restored from sessionStorage
when reloading the page after a chunk error or manual reloadNuxtApp()
call.
为避免水化错误,该函数仅在 Vue 应用挂载后才会应用,这意味着初始加载时可能会出现闪烁。
¥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.
useState
提供显式键,因为自动生成的键可能在不同的构建中不匹配。export default defineNuxtConfig({
experimental: {
restoreState: true
}
})
inlineRouteRules
使用 defineRouteRules
在页面级别定义路由规则。
¥Define route rules at the page level using defineRouteRules
.
export default defineNuxtConfig({
experimental: {
inlineRouteRules: true
}
})
将根据页面的 path
创建匹配的路由规则。
¥Matching route rules will be created, based on the page's path
.
:
阅读更多 defineRouteRules
实用程序。
¥Read more in defineRouteRules
utility.
::
renderJsonPayloads
允许渲染 JSON 负载,并支持恢复复杂类型。
¥Allows rendering of JSON payloads with support for revivifying complex types.
默认启用。
¥Enabled by default.
export default defineNuxtConfig({
experimental: {
renderJsonPayloads: true
}
})
noVueServer
禁用 Nitro 中的 Vue 服务器渲染器端点。
¥Disables Vue server renderer endpoint within Nitro.
export default defineNuxtConfig({
experimental: {
noVueServer: true
}
})
payloadExtraction
启用提取使用 nuxt generate
生成的页面的有效负载。
¥Enables extraction of payloads of pages generated with nuxt generate
.
export default defineNuxtConfig({
experimental: {
payloadExtraction: true
}
})
clientFallback
启用实验性 <NuxtClientFallback>
组件,以便在服务器端渲染 (SSR) 出现错误时在客户端渲染内容。
¥Enables the experimental <NuxtClientFallback>
component for rendering content on the client if there's an error in SSR.
export default defineNuxtConfig({
experimental: {
clientFallback: true
}
})
crossOriginPrefetch
使用 Speculation Rules API 启用跨域预取。
¥Enables cross-origin prefetch using the Speculation Rules API.
export default defineNuxtConfig({
experimental: {
crossOriginPrefetch: true
}
})
:
了解更多关于推测规则 API 的信息。
¥Read more about the Speculation Rules API.
::
viewTransition
启用 View Transition API 与客户端路由的集成。
¥Enables View Transition API integration with client-side router.
export default defineNuxtConfig({
experimental: {
viewTransition: true
}
})
:
了解更多关于视图转换 API 的信息。
¥Read more about the View Transition API.
::
writeEarlyHints
启用使用 Node 服务器时写入早期提示。
¥Enables writing of early hints when using node server.
export default defineNuxtConfig({
experimental: {
writeEarlyHints: true
}
})
componentIslands
启用对 <NuxtIsland>
和 .island.vue
文件的实验性组件岛支持。
¥Enables experimental component islands support with <NuxtIsland>
and .island.vue
files.
export default defineNuxtConfig({
experimental: {
componentIslands: true // false or 'local+remote'
}
})
:
你可以关注 GitHub 上的服务器组件路线图。
¥You can follow the server components roadmap on GitHub.
::
localLayerAliases
根据图层源和根目录解析图层内的 ~
、~~
、@
和 @@
别名。
¥Resolve ~
, ~~
, @
and @@
aliases located within layers with respect to their layer source and root directories.
默认启用。
¥Enabled by default.
export default defineNuxtConfig({
experimental: {
localLayerAliases: true
}
})
typedPages
使用 unplugin-vue-router
启用新的实验性类型路由。
¥Enable the new experimental typed router using unplugin-vue-router
.
export default defineNuxtConfig({
experimental: {
typedPages: true
}
})
开箱即用,这将启用 navigateTo
、<NuxtLink>
、router.push()
等类型的使用。
¥Out of the box, this will enable typed usage of navigateTo
, <NuxtLink>
, router.push()
and more.
你甚至可以使用 const route = useRoute('route-name')
获取页面内输入的参数。
¥You can even get typed params within a page by using const route = useRoute('route-name')
.
pnpm
而不使用 shamefully-hoist=true
,则需要将 unplugin-vue-router
安装为 devDependency 才能使此功能正常工作。watcher
设置一个备用的监视器,用作 Nuxt 的观察服务。
¥Set an alternative watcher that will be used as the watching service for Nuxt.
Nuxt 默认使用 chokidar-granular
,这将忽略从监视中排除的顶层目录(例如 node_modules
和 .git
)。
¥Nuxt uses chokidar-granular
by default, which will ignore top-level directories
(like node_modules
and .git
) that are excluded from watching.
你可以将其设置为 parcel
以使用 @parcel/watcher
,这可能会提高大型项目或 Windows 平台上的性能。
¥You can set this instead to parcel
to use @parcel/watcher
, which may improve
performance in large projects or on Windows platforms.
你还可以将其设置为 chokidar
以监视源目录中的所有文件。
¥You can also set this to chokidar
to watch all files in your source directory.
export default defineNuxtConfig({
experimental: {
watcher: 'chokidar-granular' // 'chokidar' or 'parcel' are also options
}
})
sharedPrerenderData
启用此功能会自动在预渲染的页面之间共享负载数据。当预渲染使用 useAsyncData
或 useFetch
并在不同页面获取相同数据的站点时,这可以显著提高性能。
¥Enabling this feature automatically shares 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.
export default defineNuxtConfig({
experimental: {
sharedPrerenderData: true
}
})
启用此功能时,确保数据的任何唯一键始终可解析为相同数据尤为重要。例如,如果你使用 useAsyncData
获取与特定页面相关的数据,则应提供与该数据唯一匹配的键。(useFetch
应该会自动为你执行此操作。)
¥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.)
// 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}`)
})
clientNodeCompat
使用此功能,Nuxt 将使用 unenv
自动在客户端构建中填充 Node.js 导入。
¥With this feature, Nuxt will automatically polyfill Node.js imports in the client build using unenv
.
Buffer
这样的全局变量在浏览器中工作,你需要手动注入它们。 ```ts
import { Buffer } from 'node:buffer'globalThis.Buffer = globalThis.Buffer || Buffer::
<a id="scanpagemeta"></a>
## scanPageMeta
此选项允许在构建时将 `definePageMeta` 中定义的一些路由元数据公开给模块(特别是 `alias`、`name`、`path`、`redirect`、`props` 和 `middleware`)。
¥This option allows exposing some route metadata defined in `definePageMeta` at build-time to modules (specifically `alias`, `name`, `path`, `redirect`, `props` and `middleware`).
这仅适用于静态或字符串/数组,而不适用于变量或条件赋值。有关更多信息和上下文,请参阅 [原始问题](https://github.com/nuxt/nuxt/issues/24770)。
¥This only works with static or strings/arrays rather than variables or conditional assignment. See [original issue](https://github.com/nuxt/nuxt/issues/24770) for more information and context.
也可以仅在所有路由在 `pages:extend` 中注册后才扫描页面元数据。然后将调用另一个钩子 `pages:resolved`。要启用此行为,请设置 `scanPageMeta: 'after-resolve'`。
¥It is also possible to scan page metadata only after all routes have been registered in `pages:extend`. Then another hook, `pages:resolved` will be called. To enable this behavior, set `scanPageMeta: 'after-resolve'`.
如果此功能在你的项目中导致问题,你可以禁用它。
¥You can disable this feature if it causes issues in your project.
```ts twoslash [nuxt.config.ts]
export default defineNuxtConfig({
experimental: {
scanPageMeta: false
}
})
cookieStore
启用 CookieStore 支持,以监听 Cookie 更新(如果浏览器支持)并刷新useCookie
引用值。¥Enables CookieStore support to listen for cookie updates (if supported by the browser) and refresh useCookie
ref values.export default defineNuxtConfig({
experimental: {
cookieStore: true
}
})
buildCache
基于配置和源文件的哈希值缓存 Nuxt 构建工件。¥Caches Nuxt build artifacts based on a hash of the configuration and source files.export default defineNuxtConfig({
experimental: {
buildCache: true
}
})
.nuxtrc
.npmrc
package.json
package-lock.json
yarn.lock
pnpm-lock.yaml
tsconfig.json
bun.lockb
srcDir
内文件的任何更改都将触发 Vue 客户端/服务器包的重建。Nitro 将始终重建(尽管正在进行允许 Nitro 声明其可缓存的构件及其哈希值的工作)。¥In addition, any changes to files within srcDir
will trigger a rebuild of the Vue client/server bundle. Nitro will always be rebuilt (though work is in progress to allow Nitro to announce its cacheable artifacts and their hashes).extraPageMetaExtractionKeys
definePageMeta()
宏是收集页面构建时元数据的有效方法。Nuxt 本身提供了一组受支持的键列表,用于支持一些内部功能,例如重定向、页面别名和自定义路径。¥The definePageMeta()
macro is a useful way to collect build-time meta about pages. Nuxt itself provides a set list of supported keys which is used to power some of the internal features such as redirects, page aliases and custom paths.此选项允许在使用 scanPageMeta
时传递额外的键以从页面元数据中提取。¥This option allows passing additional keys to extract from the page metadata when using scanPageMeta
.<script lang="ts" setup>
definePageMeta({
foo: 'bar'
})
</script>
export default defineNuxtConfig({
experimental: {
extraPageMetaExtractionKeys: ['foo'],
},
hooks: {
'pages:resolved' (ctx) {
// ✅ foo is available
},
},
})
NuxtPage
类型。¥This allows modules to access additional metadata from the page metadata in the build context. If you are using this within a module, it's recommended also to augment the NuxtPage
types with your keys.normalizeComponentNames
确保自动生成的 Vue 组件名称与用于自动导入组件的完整组件名称匹配。¥Ensure that auto-generated Vue component names match the full component name you would use to auto-import the component.export default defineNuxtConfig({
experimental: {
normalizeComponentNames: true
}
})
├─ components/
├─── SomeFolder/
├───── MyComponent.vue
MyComponent
。如果你想将 <KeepAlive>
与它一起使用,或者在 Vue DevTools 中识别它,则需要使用此组件。¥In this case, the component name would be MyComponent
, as far as Vue is concerned. If you wanted to use <KeepAlive>
with it, or identify it in the Vue DevTools, you would need to use this component.但为了自动导入它,你需要使用 SomeFolderMyComponent
。¥But in order to auto-import it, you would need to use SomeFolderMyComponent
.通过设置 experimental.normalizeComponentNames
,这两个值将匹配,Vue 将生成一个与 Nuxt 组件命名模式匹配的组件名称。¥By setting experimental.normalizeComponentNames
, these two values match, and Vue will generate a component name that matches the Nuxt pattern for component naming.spaLoadingTemplateLocation
在渲染纯客户端页面(使用ssr: false
)时,我们可选择渲染一个加载屏幕(来自 app/spa-loading-template.html
)。¥When rendering a client-only page (with ssr: false
), we optionally render a loading screen (from app/spa-loading-template.html
).可以将其设置为 within
,这样会将其渲染成如下形式:¥It can be set to within
, which will render it like this:<div id="__nuxt">
<!-- spa loading template -->
</div>
body
,使其与 Nuxt 应用根目录一起渲染:¥Alternatively, you can render the template alongside the Nuxt app root by setting it to body
:<div id="__nuxt"></div>
<!-- spa loading template -->
browserDevtoolsTiming
在浏览器开发者工具中启用 Nuxt hooks 的性能标记。这会添加性能标记,你可以在基于 Chromium 的浏览器的“性能”选项卡中跟踪这些标记,这对于调试和优化性能非常有用。¥Enables performance markers for Nuxt hooks in browser devtools. This adds performance markers that you can track in the Performance tab of Chromium-based browsers, which is useful for debugging and optimizing performance.此功能在开发模式下默认启用。如果你需要禁用此功能,可以执行以下操作:¥This is enabled by default in development mode. If you need to disable this feature, it is possible to do so:export default defineNuxtConfig({
experimental: {
browserDevtoolsTiming: false
}
})
debugModuleMutation
在模块上下文中记录nuxt.options
的变更,帮助调试模块在 Nuxt 初始化阶段所做的配置更改。¥Records mutations to nuxt.options
in module context, helping to debug configuration changes made by modules during the Nuxt initialization phase.启用 debug
模式后,此功能默认启用。如果你需要禁用此功能,可以执行以下操作:¥This is enabled by default when debug
mode is enabled. If you need to disable this feature, it is possible to do so:要显式启用它:¥To enable it explicitly:export default defineNuxtConfig({
experimental: {
debugModuleMutation: true
}
})
lazyHydration
这将为<Lazy>
组件启用混合策略,通过将组件的混合推迟到需要它们时来提高性能。¥This enables hydration strategies for <Lazy>
components, which improves performance by deferring hydration of components until they're needed.惰性加载默认启用,但你可以禁用此功能:¥Lazy hydration is enabled by default, but you can disable this feature:export default defineNuxtConfig({
experimental: {
lazyHydration: false
}
})
templateImportResolution
控制如何解析 Nuxt 模板中的导入。默认情况下,Nuxt 会尝试解析模板中相对于添加它们的模块的导入。¥Controls how imports in Nuxt templates are resolved. By default, Nuxt attempts to resolve imports in templates relative to the module that added them.此功能默认启用,因此如果你在某些环境中遇到解析冲突,可以禁用此行为:¥This is enabled by default, so if you're experiencing resolution conflicts in certain environments, you can disable this behavior:export default defineNuxtConfig({
experimental: {
templateImportResolution: false
}
})
decorators
此选项允许在整个 Nuxt/Nitro 应用中启用装饰器语法,该应用由 esbuild 提供支持。¥This option enables enabling decorator syntax across your entire Nuxt/Nitro app, powered by esbuild.长期以来,TypeScript 一直通过compilerOptions.experimentalDecorators
支持装饰器。此实现早于 TC39 标准化过程。现在,装饰器是 第三阶段提案,并且在 TS 5.0+ 中无需特殊配置即可支持(参见 https://github.com/microsoft/TypeScript/pull/52582 和 https://devblogs.microsoft.com/typescript/announcing-typescript-5-0-beta/#decorators)。¥For a long time, TypeScript has had support for decorators via compilerOptions.experimentalDecorators
. This implementation predated the TC39 standardization process. Now, decorators are a Stage 3 Proposal, and supported without special configuration in TS 5.0+ (see https://github.com/microsoft/TypeScript/pull/52582 and https://devblogs.microsoft.com/typescript/announcing-typescript-5-0-beta/#decorators).启用 experimental.decorators
可支持 TC39 提案,而非 TypeScript 之前的 compilerOptions.experimentalDecorators
实现。¥Enabling experimental.decorators
enables support for the TC39 proposal, NOT for TypeScript's previous compilerOptions.experimentalDecorators
implementation.用法
¥Usageexport default defineNuxtConfig({
experimental: {
decorators: true,
},
})
function something (_method: () => unknown) {
return () => 'decorated'
}
class SomeClass {
@something
public someMethod () {
return 'initial'
}
}
const value = new SomeClass().someMethod()
// this will return 'decorated'
purgeCachedData
Nuxt 将自动清除useAsyncData
和 nuxtApp.static.data
中的缓存数据。这有助于防止内存泄漏并确保在需要时加载新数据,但可以禁用它:¥Nuxt will automatically purge cached data from useAsyncData
and nuxtApp.static.data
. This helps prevent memory leaks
and ensures fresh data is loaded when needed, but it is possible to disable it:export default defineNuxtConfig({
experimental: {
purgeCachedData: false
}
})
granularCachedData
在刷新useAsyncData
和 useFetch
的数据时,是否调用并使用 getCachedData
的结果(无论是通过 watch
、refreshNuxtData()
还是手动调用 refresh()
)。¥Whether to call and use the result from getCachedData
when refreshing data for useAsyncData
and useFetch
(whether by watch
, refreshNuxtData()
, or a manual refresh()
call.export default defineNuxtConfig({
experimental: {
granularCachedData: true
}
})
pendingWhenIdle
如果设置为false
,则从 useAsyncData
、useFetch
、useLazyAsyncData
和 useLazyFetch
返回的 pending
对象将是一个计算属性,仅当 status
也处于待处理状态时,该属性才为 true
。¥If set to false
, the pending
object returned from useAsyncData
, useFetch
, useLazyAsyncData
and useLazyFetch
will be a computed property that is true
only when status
is also pending.这意味着当 immediate: false
被传递时,pending
将为 false
,直到发出第一个请求。¥That means that when immediate: false
is passed, pending
will be false
until the first request is made.export default defineNuxtConfig({
experimental: {
pendingWhenIdle: false
}
})