app.config.ts
Nuxt 提供了一个 app.config 配置文件,用于在你的应用程序中 公开响应式配置,并且能够在生命周期内或使用 Nuxt 插件并在 HMR(热模块替换)的支持下编辑它,从而在运行时更新它。
你可以使用 app.config.ts 文件轻松地提供运行时应用程序配置。它可以具有 .ts、.js 或 .mjs 扩展名。
export default defineAppConfig({
foo: 'bar'
})
app.config 文件中。它会暴露给用户客户端包。用法
要将配置和环境变量暴露给应用程序的其余部分,你需要在 app.config 文件中定义配置。
export default defineAppConfig({
theme: {
primaryColor: '#ababab'
}
})
现在,我们可以在服务器端渲染页面和在浏览器中使用 useAppConfig composable 时全局访问 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 尝试从提供的应用程序配置自动生成 TypeScript 接口,因此你无需自己键入它。
但是,在某些情况下,你可能希望自己键入它。你可能想要键入两种可能的事物。
App Config 输入
模块作者在声明设置应用程序配置时有效的 输入 选项时,可能会使用 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 {}
App Config 输出
如果你想键入调用 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。
此策略使用 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 在没有完整 Vue 组件支持的情况下处理应用程序配置。
虽然可以在 Nitro 配置中使用 Vite 插件作为一种变通方法,但不建议这样做:
export default defineNuxtConfig({
nitro: {
vite: {
plugins: [vue()]
}
}
})
相关问题: