运行时配置
了解如何将 Nuxt 2 运行时配置迁移到 Nuxt 3。
如果您希望在 Nuxt 3 应用程序中引用环境变量,则需要使用运行时配置。
在组件中引用这些变量时,您必须在设置方法(或 Nuxt 插件)中使用 useRuntimeConfig
可组合函数。
在应用程序的 server/
部分,您可以无需任何导入即可使用 useRuntimeConfig
。
迁移
- 将您在应用程序中使用的任何环境变量添加到
nuxt.config
文件的runtimeConfig
属性中。 - 在应用程序的 Vue 部分中,将
process.env
迁移到useRuntimeConfig
。
export default defineNuxtConfig({
runtimeConfig: {
// Private config that is only available on the server
apiSecret: '123',
// Config within public will be also exposed to the client
public: {
apiBase: '/api',
},
},
})
<script setup lang="ts">
const config = useRuntimeConfig()
// instead of process.env you will now access config.public.apiBase
console.log(config.public.apiBase)
</script>
export default defineEventhandler((event) => {
const config = useRuntimeConfig(event)
// In server, you can now access config.apiSecret, in addition to config.public
console.log(config.apiSecret)
console.log(config.public.apiBase)
})
# Runtime config values are automatically replaced by matching environment variables at runtime
NUXT_API_SECRET=api_secret_token
NUXT_PUBLIC_API_BASE=https://nuxtjs.org.cn