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
文件中放置任何秘密值。它将暴露给用户客户端捆绑包。使用
要将配置和环境变量暴露给应用程序的其余部分,你需要在 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>
应用程序配置类型
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'],
})
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 处理应用程序配置时没有完全的 Vue 组件支持。
尽管可以在 Nitro 配置中使用 Vite 插件作为一种变通方法,但这种方法不推荐
nuxt.config.ts
export default defineNuxtConfig({
nitro: {
vite: {
plugins: [vue()],
},
},
})
使用此变通方法可能会导致意外行为和错误。Vue 插件是许多在 Nitro 上下文中不可用的插件之一。
相关问题
Nitro v3 将通过删除对应用程序配置的支持来解决这些限制。你可以在此拉取请求.