app.config.ts
Nuxt 提供了一个 app/app.config.ts 配置文件,用于在应用程序中公开响应式配置,并支持在生命周期内或通过 Nuxt 插件在运行时对其进行更新,同时支持通过 HMR(热模块替换)进行编辑。
你可以使用 app.config.ts 文件轻松提供运行时应用配置。它可以具有 .ts、.js 或 .mjs 扩展名。
export default defineAppConfig({
foo: 'bar',
})
app.config 文件中放置任何机密值,因为它会被暴露给用户侧的客户端包。使用
要向应用的其余部分公开配置和环境变量,你需要在 app.config 文件中定义配置。
export default defineAppConfig({
theme: {
primaryColor: '#ababab',
},
})
现在,我们可以通过 useAppConfig 组合式函数,在服务器端渲染页面和浏览器端统一访问 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 会尝试自动从提供的 app config 生成 TypeScript 接口,因此你无需手动为其编写类型。
不过,在某些情况下,你可能想要手动定义类型。有两种情况你可能需要定义类型:
App Config 输入 (Input)
AppConfigInput 可能被模块作者使用,用以声明设置 app config 时的有效输入选项。这不会影响 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 输出 (Output)
如果你想为调用 useAppConfig() 的结果定义类型,那么你需要扩展 AppConfig。
AppConfig 类型时请小心,因为这会覆盖 Nuxt 从你实际定义的 app config 中推断出的类型。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'],
})
export default defineAppConfig({
// Overwrite default array value by using a merger function
array: () => ['bonjour'],
})
已知限制
截至 Nuxt v3.3,app.config.ts 文件与 Nitro 共享,这导致了以下限制:
- 你不能直接在
app.config.ts中导入 Vue 组件。 - 某些自动导入在 Nitro 上下文中不可用。
这些限制是因为 Nitro 在处理 app config 时没有完全的 Vue 组件支持。
虽然可以通过在 Nitro 配置中使用 Vite 插件作为替代方案,但不建议这样做。
export default defineNuxtConfig({
nitro: {
vite: {
plugins: [vue()],
},
},
})
相关议题