Lzh on GitHub

app.config.ts

使用 App Config 文件在你的应用程序中公开响应式配置。

Nuxt 提供了一个 app.config 配置文件,用于在你的应用程序中 公开响应式配置,并且能够在生命周期内或使用 Nuxt 插件并在 HMR(热模块替换)的支持下编辑它,从而在运行时更新它。

你可以使用 app.config.ts 文件轻松地提供运行时应用程序配置。它可以具有 .ts.js.mjs 扩展名。

app.config.ts
export default defineAppConfig({
  foo: 'bar'
})
不要将任何秘密值放在 app.config 文件中。它会暴露给用户客户端包。
当配置自定义 srcDir 时,请确保将 app.config 文件放在新的 srcDir 路径的根目录下。

用法

要将配置和环境变量暴露给应用程序的其余部分,你需要在 app.config 文件中定义配置。

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

现在,我们可以在服务器端渲染页面和在浏览器中使用 useAppConfig composable 时全局访问 theme

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

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

updateAppConfig 实用程序可用于在运行时更新 app.config

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

const newAppConfig = { foo: 'baz' }

updateAppConfig(newAppConfig)

console.log(appConfig) // { foo: 'baz' }
</script>
阅读更多关于 updateAppConfig 实用程序的信息。

类型化 App Config

Nuxt 尝试从提供的应用程序配置自动生成 TypeScript 接口,因此你无需自己键入它。

但是,在某些情况下,你可能希望自己键入它。你可能想要键入两种可能的事物。

App Config 输入

模块作者在声明设置应用程序配置时有效的 输入 选项时,可能会使用 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 {}

App Config 输出

如果你想键入调用 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

此策略使用 Function Merger 实现,该合并器允许为 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 将通过移除对应用程序配置的支持来解决这些限制。 你可以在此 pull request 中跟踪进度。