app.config.ts

使用 App Config 檔案在應用程式中暴露響應式配置。

Nuxt 提供了一個 app/app.config.ts 配置檔案,用於在應用程式中暴露響應式配置,並且可以在生命週期內或使用 Nuxt 外掛在執行時更新,並透過 HMR(熱模組替換)進行編輯。

你可以使用 app.config.ts 檔案輕鬆提供執行時應用程式配置。它可以是 .ts.js.mjs 副檔名。

app/app.config.ts
export default defineAppConfig({
  foo: 'bar',
})
不要在 app.config 檔案中放置任何秘密值。它將暴露給使用者客戶端捆綁包。
配置自定義 srcDir 時,請確保將 app.config 檔案放置在新 srcDir 路徑的根目錄。

使用

要將配置和環境變數暴露給應用程式的其餘部分,你需要在 app.config 檔案中定義配置。

app/app.config.ts
export default defineAppConfig({
  theme: {
    primaryColor: '#ababab',
  },
})

現在,我們可以使用 useAppConfig 可組合項,在伺服器渲染頁面和瀏覽器中普遍訪問 theme

app/pages/index.vue
<script setup lang="ts">
const appConfig = useAppConfig()

console.log(appConfig.theme)
</script>

可以使用 updateAppConfig 工具在執行時更新 app.config

app/pages/index.vue
<script setup>
const appConfig = useAppConfig() // { foo: 'bar' }

const newAppConfig = { foo: 'baz' }

updateAppConfig(newAppConfig)

console.log(appConfig) // { foo: 'baz' }
</script>
閱讀更多關於 updateAppConfig 工具的資訊。

應用程式配置型別

Nuxt 嘗試從提供的應用程式配置自動生成 TypeScript 介面,這樣你就不必自己編寫型別。

但是,在某些情況下,你可能希望自己編寫型別。有兩種可能需要型別化的內容。

應用程式配置輸入

AppConfigInput 可能被模組作者使用,他們聲明瞭設定應用程式配置時有效的輸入選項。這不會影響 useAppConfig() 的型別。

index.d.ts
declare module 'nuxt/schema' {
  interface AppConfigInput {
    /** Theme configuration */
    theme?: {
      /** Primary app color */
      primaryColor?: string
    }
  }
}

// It is always important to ensure you import/export something when augmenting a type
export {}

應用程式配置輸出

如果你想為呼叫 useAppConfig() 的結果新增型別,那麼你將需要擴充套件 AppConfig

在為 AppConfig 新增型別時要小心,因為你將覆蓋 Nuxt 從你實際定義的應用程式配置推斷出的型別。
index.d.ts
declare module 'nuxt/schema' {
  interface AppConfig {
    // This will entirely replace the existing inferred `theme` property
    theme: {
      // You might want to type this value to add more specific types than Nuxt can infer,
      // such as string literal types
      primaryColor?: 'red' | 'blue'
    }
  }
}

// It is always important to ensure you import/export something when augmenting a type
export {}

合併策略

Nuxt 為應用程式 中的 AppConfig 使用自定義合併策略。

此策略使用函式合併器實現,它允許為 app.config 中所有值為陣列的鍵定義自定義合併策略。

函式合併器只能在擴充套件層中使用,不能在專案的主要 app.config 中使用。

以下是如何使用

export default defineAppConfig({
  // Default array value
  array: ['hello'],
})

已知限制

從 Nuxt v3.3 開始,app.config.ts 檔案與 Nitro 共享,導致以下限制:

  1. 你不能直接在 app.config.ts 中匯入 Vue 元件。
  2. 在 Nitro 上下文中,某些自動匯入不可用。

這些限制的發生是因為 Nitro 處理應用程式配置時沒有完全的 Vue 元件支援。

儘管可以在 Nitro 配置中使用 Vite 外掛作為一種變通方法,但這種方法不推薦

nuxt.config.ts
export default defineNuxtConfig({
  nitro: {
    vite: {
      plugins: [vue()],
    },
  },
})
使用此變通方法可能會導致意外行為和錯誤。Vue 外掛是許多在 Nitro 上下文中不可用的外掛之一。

相關問題

Nitro v3 將透過刪除對應用程式配置的支援來解決這些限制。你可以在此拉取請求.