Nuxt 提供了一个 app/app.config.ts 配置文件,用于在你的应用程序中暴露响应式配置,并且能够在生命周期内或使用 Nuxt 插件在运行时更新它,并通过 HMR(热模块替换)进行编辑。
你可以使用 app.config.ts 文件轻松提供运行时应用程序配置。它可以是 .ts、.js 或 .mjs 扩展名。
export default defineAppConfig({
foo: 'bar',
})
app.config 文件中放置任何秘密值。它会暴露给用户客户端 bundle。要将配置和环境变量暴露给应用程序的其余部分,你需要在 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>
Nuxt 尝试从提供的应用程序配置中自动生成 TypeScript 接口,因此你无需手动输入。
但是,在某些情况下,你可能希望自己输入。有两种可能需要类型化的事情。
AppConfigInput 可能被模块作者使用,他们声明设置应用程序配置时有效的输入选项。这不会影响 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 {}
如果你想对调用 useAppConfig() 的结果进行类型化,那么你需要扩展 AppConfig。
AppConfig 进行类型化时要小心,因为你会覆盖 Nuxt 从你实际定义的应用程序配置中推断出的类型。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'],
})
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 在没有完整的 Vue 组件支持的情况下处理应用程序配置。
虽然可以通过在 Nitro 配置中使用 Vite 插件作为一种变通方法,但这种方法不推荐使用
export default defineNuxtConfig({
nitro: {
vite: {
plugins: [vue()],
},
},
})
相关问题