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 中值为数组的每个键定义自定义合并策略。

函数合并器只能在扩展层(extended layers)中使用,而不能在项目的主 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()],
    },
  },
})
使用此变通方法可能会导致意外行为和错误。Vue 插件只是众多在 Nitro 上下文中不可用的插件之一。

相关问题:

Nitro v3 将通过移除对 app config 的支持来解决这些限制。 您可以在此拉取请求中跟踪进度:this pull request