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 文件中放置任何秘密值。它会暴露给用户客户端 bundle。
配置自定义的 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 将通过删除对应用程序配置的支持来解决这些限制。你可以在此拉取请求.