运行时配置

了解如何将 Nuxt 2 的运行时配置迁移到 Nuxt 3。

如果你希望在 Nuxt 3 应用中引用环境变量,你需要使用运行时配置(runtime config)。

在组件中引用这些变量时,需要在 setup 方法(或 Nuxt 插件)中使用 useRuntimeConfig 组合式函数。

在应用的 server/ 部分,可以在不导入的情况下使用 useRuntimeConfig

Read more in Docs > 4 X > Guide > Going Further > Runtime Config.

迁移

  1. 将应用中使用的任何环境变量添加到 nuxt.config 文件的 runtimeConfig 属性中。
  2. 在应用的 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',
    },
  },
})