app.config.ts
Nuxt 提供一個 app.config
設定檔,以在您的應用程式中公開響應式設定,並能夠在生命週期內或使用 nuxt 外掛程式在執行階段更新它,並使用 HMR(熱模組替換)進行編輯。
您可以使用 app.config.ts
檔案輕鬆提供執行階段應用程式設定。它可以具有 .ts
、.js
或 .mjs
副檔名。
export default defineAppConfig({
foo: 'bar'
})
app.config
檔案中。它會暴露給使用者用戶端套件。用法
若要將設定和環境變數公開給應用程式的其餘部分,您需要在 app.config
檔案中定義設定。
export default defineAppConfig({
theme: {
primaryColor: '#ababab'
}
})
現在,我們可以使用 useAppConfig
composable,在伺服器端渲染頁面和瀏覽器中通用地存取 theme
。
<script setup lang="ts">
const appConfig = useAppConfig()
console.log(appConfig.theme)
</script>
updateAppConfig
工具程式可用於在執行階段更新 app.config
。
<script setup>
const appConfig = useAppConfig() // { foo: 'bar' }
const newAppConfig = { foo: 'baz' }
updateAppConfig(newAppConfig)
console.log(appConfig) // { foo: 'baz' }
</script>
App Config 的類型標註
Nuxt 嘗試從提供的應用程式設定自動產生 TypeScript 介面,因此您不必自行標註其類型。
但是,在某些情況下,您可能想要自行標註其類型。您可能想要標註兩種可能的內容。
App Config 輸入
AppConfigInput
可能供模組作者使用,他們宣告設定應用程式設定時有效的輸入選項。這不會影響 useAppConfig()
的類型。
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 {}
App Config 輸出
如果您想要標註呼叫 useAppConfig()
的結果類型,那麼您會想要擴充 AppConfig
。
AppConfig
的類型時請小心,因為您將覆寫 Nuxt 從您實際定義的應用程式設定推斷出的類型。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 對於應用程式 layers 中的 AppConfig
使用自訂合併策略。
此策略是使用 Function Merger 實作的,它允許為 app.config
中每個以陣列作為值的鍵定義自訂合併策略。
app.config
中使用。以下是如何使用的一個範例
export default defineAppConfig({
// Default array value
array: ['hello'],
})
已知限制
截至 Nuxt v3.3,app.config.ts
檔案與 Nitro 共用,這導致以下限制
- 您無法直接在
app.config.ts
中匯入 Vue 元件。 - 某些自動匯入在 Nitro 環境中不可用。
發生這些限制的原因是 Nitro 在沒有完整 Vue 元件支援的情況下處理應用程式設定。
雖然可以在 Nitro 設定中使用 Vite 外掛程式作為變通方法,但不建議使用這種方法
export default defineNuxtConfig({
nitro: {
vite: {
plugins: [vue()]
}
}
})
相關問題
Nitro v3 將透過移除對 app config 的支援來解決這些限制。您可以在此 pull request 中追蹤進度。