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()],
},
},
})
相关问题: