透過超過 100 個秘訣的合輯來學習 Nuxt!

實驗性功能

啟用 Nuxt 實驗性功能以解鎖新的可能性。

Nuxt 實驗性功能可以在 Nuxt 設定檔中啟用。

在內部,Nuxt 使用 @nuxt/schema 來定義這些實驗性功能。您可以參考 API 文件原始碼 以獲得更多資訊。

請注意,這些功能為實驗性質,未來可能會被移除或修改。

asyncContext

啟用原生 async context,使其在 Nuxt 和 Nitro 中可被巢狀 composable 存取。這開啟了在 async composable 內部使用 composable 的可能性,並降低取得 Nuxt instance is unavailable 錯誤的機率。

nuxt.config.ts
export default 
defineNuxtConfig
({
experimental
: {
asyncContext
: true
} })
請參閱 GitHub pull request 上的完整說明。

asyncEntry

啟用為 Vue bundle 生成異步入口點,以輔助模組聯邦支援。

nuxt.config.ts
export default 
defineNuxtConfig
({
experimental
: {
asyncEntry
: true
} })

externalVue

在建置時將 vue@vue/*vue-router 外部化。

預設啟用。

nuxt.config.ts
export default 
defineNuxtConfig
({
experimental
: {
externalVue
: true
} })
此功能很可能在不久的將來被移除。

treeshakeClientOnly

從伺服器 bundle 中 tree shake 僅限客戶端元件的內容。

預設啟用。

nuxt.config.ts
export default 
defineNuxtConfig
({
experimental
: {
treeshakeClientOnly
: true
} })

emitRouteChunkError

當載入 vite/webpack chunk 發生錯誤時,發出 app:chunkError 鉤子。預設行為是在導航到新路由時,如果 chunk 載入失敗,則重新載入新路由。

如果您將此設定為 'automatic-immediate',Nuxt 將立即重新載入當前路由,而不是等待導航。這對於非導航觸發的 chunk 錯誤很有用,例如,當您的 Nuxt 應用程式無法載入 lazy component 時。此行為的潛在缺點是不必要的重新載入,例如,當您的應用程式不需要導致錯誤的 chunk 時。

您可以將此設定為 false 來停用自動處理,或將其設定為 manual 來手動處理 chunk 錯誤。

nuxt.config.ts
export default 
defineNuxtConfig
({
experimental
: {
emitRouteChunkError
: 'automatic' // or 'automatic-immediate', 'manual' or false
} })

restoreState

允許在 chunk 錯誤後重新載入頁面或手動呼叫 reloadNuxtApp() 時,從 sessionStorage 還原 Nuxt 應用程式狀態。

為了避免 hydration 錯誤,它只會在 Vue 應用程式掛載後應用,這意味著在初始載入時可能會出現閃爍。

在啟用此功能之前請仔細考慮,因為它可能會導致意外行為,並考慮為 useState 提供明確的 key,因為自動生成的 key 可能在不同建置之間不匹配。
nuxt.config.ts
export default 
defineNuxtConfig
({
experimental
: {
restoreState
: true
} })

inlineRouteRules

使用 defineRouteRules 在頁面層級定義路由規則。

nuxt.config.ts
export default 
defineNuxtConfig
({
experimental
: {
inlineRouteRules
: true
} })

將根據頁面的 path 建立匹配的路由規則。

defineRouteRules 工具程式中閱讀更多資訊。
文件 > 指南 > 概念 > 渲染#混合渲染 中閱讀更多資訊。

renderJsonPayloads

允許渲染 JSON payload,並支援復甦複雜類型。

預設啟用。

nuxt.config.ts
export default 
defineNuxtConfig
({
experimental
: {
renderJsonPayloads
: true
} })

noVueServer

停用 Nitro 內的 Vue 伺服器渲染器端點。

nuxt.config.ts
export default 
defineNuxtConfig
({
experimental
: {
noVueServer
: true
} })

payloadExtraction

啟用提取使用 nuxt generate 生成的頁面的 payload。

nuxt.config.ts
export default 
defineNuxtConfig
({
experimental
: {
payloadExtraction
: true
} })

clientFallback

啟用實驗性的 <NuxtClientFallback> 元件,以便在 SSR 中發生錯誤時在客戶端渲染內容。

nuxt.config.ts
export default 
defineNuxtConfig
({
experimental
: {
clientFallback
: true
} })

crossOriginPrefetch

啟用使用 Speculation Rules API 的跨域預先擷取。

nuxt.config.ts
export default 
defineNuxtConfig
({
experimental
: {
crossOriginPrefetch
: true
} })
閱讀更多關於 Speculation Rules API 的資訊。

viewTransition

啟用 View Transition API 與客戶端路由器的整合。

nuxt.config.ts
export default 
defineNuxtConfig
({
experimental
: {
viewTransition
: true
} })
深入了解 View Transition API

writeEarlyHints

啟用使用 node server 時寫入 early hints。

nuxt.config.ts
export default 
defineNuxtConfig
({
experimental
: {
writeEarlyHints
: true
} })

componentIslands

啟用實驗性的 component islands 支援,搭配 <NuxtIsland>.island.vue 檔案。

nuxt.config.ts
export default 
defineNuxtConfig
({
experimental
: {
componentIslands
: true // false or 'local+remote'
} })
請參閱 文件 > 指南 > 目錄結構 > Components#server Components 章節以了解更多資訊。
您可以在 GitHub 上追蹤 server components 的 roadmap。

configSchema

啟用 config schema 支援。

預設啟用。

nuxt.config.ts
export default 
defineNuxtConfig
({
experimental
: {
configSchema
: true
} })

polyfillVueUseHead

為模組、外掛程式或依賴舊版 @vueuse/head API 的使用者程式碼新增相容性層。

nuxt.config.ts
export default 
defineNuxtConfig
({
experimental
: {
polyfillVueUseHead
: false
} })

respectNoSSRHeader

允許透過設定 x-nuxt-no-ssr header 來停用 Nuxt SSR 回應。

nuxt.config.ts
export default 
defineNuxtConfig
({
experimental
: {
respectNoSSRHeader
: false
} })

localLayerAliases

解析位於 layers 內的 ~~~@@@ 別名,並以其 layer 來源和根目錄為基準。

預設啟用。

nuxt.config.ts
export default 
defineNuxtConfig
({
experimental
: {
localLayerAliases
: true
} })

typedPages

啟用使用 unplugin-vue-router 的全新實驗性 typed router。

nuxt.config.ts
export default 
defineNuxtConfig
({
experimental
: {
typedPages
: true
} })

此功能開箱即用,將啟用 navigateTo<NuxtLink>router.push() 等功能的類型化用法。

您甚至可以使用 const route = useRoute('route-name') 在頁面中取得類型化的 params。

如果您使用 pnpm 且未設定 shamefully-hoist=true,您需要安裝 unplugin-vue-router 作為 devDependency,此功能才能運作。
觀看 Daniel Roe 解釋 Nuxt 中類型安全路由的影片。

watcher

設定將用作 Nuxt watching 服務的替代 watcher。

Nuxt 預設使用 chokidar-granular,它會忽略從監看中排除的頂層目錄(例如 node_modules.git)。

您可以將其設定為 parcel 以使用 @parcel/watcher,這可能會提高大型專案或 Windows 平台上的效能。

您也可以將其設定為 chokidar 以監看來源目錄中的所有檔案。

nuxt.config.ts
export default 
defineNuxtConfig
({
experimental
: {
watcher
: 'chokidar-granular' // 'chokidar' or 'parcel' are also options
} })

sharedPrerenderData

啟用此功能會自動在預先渲染的頁面之間共享 payload data。當預先渲染使用 useAsyncDatauseFetch 並在不同頁面中提取相同資料的網站時,這可以顯著提高效能。

nuxt.config.ts
export default 
defineNuxtConfig
({
experimental
: {
sharedPrerenderData
: true
} })
觀看 Alexander Lichter 關於實驗性 sharedPrerenderData 設定的影片。

啟用此功能時,特別重要的是確保資料的任何唯一 key 始終可以解析為相同的資料。例如,如果您使用 useAsyncData 來提取與特定頁面相關的資料,則應提供一個唯一匹配該資料的 key。(useFetch 應該會自動為您執行此操作。)

// 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 在 client build 中自動 polyfill Node.js imports。

為了使像 Buffer 這樣的全域變數在瀏覽器中運作,您需要手動注入它們。
import { Buffer } from 'node:buffer'

globalThis.Buffer = globalThis.Buffer || Buffer

scanPageMeta

此選項允許在 build-time 將 definePageMeta 中定義的某些路由元數據公開給模組(特別是 aliasnamepathredirect)。

這僅適用於靜態或字串/陣列,而不適用於變數或條件賦值。請參閱 原始 issue 以取得更多資訊和上下文。

也可以在所有路由都已在 pages:extend 中註冊後才掃描頁面元數據。然後將呼叫另一個 hook,pages:resolved。若要啟用此行為,請設定 scanPageMeta: 'after-resolve'

如果此功能在您的專案中引起問題,您可以停用它。

nuxt.config.ts
export default 
defineNuxtConfig
({
experimental
: {
scanPageMeta
: false
} })

cookieStore

啟用 CookieStore 支援以監聽 cookie 更新(如果瀏覽器支援)並重新整理 useCookie ref 值。

nuxt.config.ts
export default 
defineNuxtConfig
({
experimental
: {
cookieStore
: true
} })
深入了解 CookieStore

buildCache

根據組態和原始碼檔案的雜湊值快取 Nuxt build artifacts。

nuxt.config.ts
export default 
defineNuxtConfig
({
experimental
: {
buildCache
: true
} })

啟用後,對以下檔案的變更將觸發完整重建

目錄結構
.nuxtrc
.npmrc
package.json
package-lock.json
yarn.lock
pnpm-lock.yaml
tsconfig.json
bun.lockb

此外,對 srcDir 內檔案的任何變更都將觸發 Vue client/server bundle 的重建。Nitro 將始終重建(儘管正在進行工作以允許 Nitro 公告其可快取的 artifacts 及其雜湊值)。

最多保留 10 個快取 tarball。

extraPageMetaExtractionKeys

definePageMeta() macro 是一種收集頁面 build-time meta 的實用方法。Nuxt 本身提供了一組受支援的 keys 列表,用於支援某些內部功能,例如 redirects、page aliases 和 custom paths。

此選項允許在使用 scanPageMeta 時傳遞額外的 keys 以從頁面元數據中提取。

<script lang="ts" setup>
definePageMeta({
  foo: 'bar'
})
</script>
export default defineNuxtConfig({
  experimental: {
    extraPageMetaExtractionKeys: ['foo'],
  },
  hooks: {
    'pages:resolved' (ctx) {
      // ✅ foo is available
    },
  },
})

這允許模組在 build context 中存取頁面元數據中的額外元數據。如果您在模組中使用此功能,建議也 使用您的 keys 擴充 NuxtPage 類型

normalizeComponentNames

確保自動產生的 Vue component 名稱與您用於自動匯入 component 的完整 component 名稱相符。

nuxt.config.ts
export default 
defineNuxtConfig
({
experimental
: {
normalizeComponentNames
: true
} })

預設情況下,如果您未手動設定,Vue 將會指派一個符合 component 檔案名稱的 component 名稱。

目錄結構
├─ components/
├─── SomeFolder/
├───── MyComponent.vue

在這種情況下,就 Vue 而言,component 名稱將為 MyComponent。如果您想將 <KeepAlive> 與其一起使用,或在 Vue DevTools 中識別它,則需要使用此 component。

但是為了自動匯入它,您需要使用 SomeFolderMyComponent

透過設定 experimental.normalizeComponentNames,這兩個值會匹配,並且 Vue 將產生一個符合 Nuxt component 命名模式的 component 名稱。

spaLoadingTemplateLocation

當渲染僅限於 client 端的頁面(使用 ssr: false)時,我們可以選擇性地渲染載入畫面(來自 app/spa-loading-template.html)。

可以將其設定為 within,這將像這樣渲染它

<div id="__nuxt">
  <!-- spa loading template -->
</div>

或者,您可以將其設定為 body,將 template 與 Nuxt app root 一起渲染

<div id="__nuxt"></div>
<!-- spa loading template -->

這避免了在 hydrating 僅限 client 端的頁面時出現白屏閃爍。

decorators

此選項啟用在您的整個 Nuxt/Nitro app 中啟用 decorator syntax,由 esbuild 提供技術支援。

長期以來,TypeScript 一直透過 compilerOptions.experimentalDecorators 支援 decorators。此實作早於 TC39 標準化流程。現在,decorators 是 Stage 3 Proposal,並且在 TS 5.0+ 中無需特殊組態即可支援(請參閱 https://github.com/microsoft/TypeScript/pull/52582https://devblogs.microsoft.com/typescript/announcing-typescript-5-0-beta/#decorators)。

啟用 experimental.decorators 啟用對 TC39 proposal 的支援,而非 TypeScript 之前的 compilerOptions.experimentalDecorators 實作。

請注意,在最終納入 JS 標準之前,可能會有一些變更。

用法

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    decorators: true,
  },
})
app.vue
function something (_method: () => unknown) {
  return () => 'decorated'
}

class SomeClass {
  @something
  public someMethod () {
    return 'initial'
  }
}

const value = new SomeClass().someMethod()
// this will return 'decorated'