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 工具的更多信息。

为 App Config 添加类型定义

Nuxt 会尝试自动从提供的 app config 生成 TypeScript 接口,因此你无需手动为其编写类型。

不过,在某些情况下,你可能想要手动定义类型。有两种情况你可能需要定义类型:

App Config 输入 (Input)

AppConfigInput 可能被模块作者使用,用以声明设置 app config 时的有效输入选项。这不会影响 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 输出 (Output)

如果你想为调用 useAppConfig() 的结果定义类型,那么你需要扩展 AppConfig

在定义 AppConfig 类型时请小心,因为这会覆盖 Nuxt 从你实际定义的 app config 中推断出的类型。
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 对应用程序各层 (layers) 中的 AppConfig 使用自定义合并策略。

此策略是通过以下方式实现的:函数合并器 (Function Merger),它允许为 app.config 中值为数组的每个键定义自定义合并策略。

函数合并器只能在扩展的 layer 中使用,不能在项目主 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 在处理 app config 时没有完全的 Vue 组件支持。

虽然可以通过在 Nitro 配置中使用 Vite 插件作为替代方案,但不建议这样做。

nuxt.config.ts
export default defineNuxtConfig({
  nitro: {
    vite: {
      plugins: [vue()],
    },
  },
})
使用此替代方案可能会导致意外行为和 Bug。Vue 插件是在 Nitro 上下文中不可用的众多插件之一。

相关议题

Nitro v3 将通过移除对 app config 的支持来解决这些限制。你可以跟踪其进展:此 Pull Request.