为什么runtimeConfig在Nuxt 3中看不到环境变量?

Sha*_*nov 7 vue.js nuxt.js nuxtjs3

  1. yarn build没有.env文件
  2. 将文件添加.env到项目中
  3. 我愿意yarn start
  4. 将 打印useRuntimeConfig().public.baseURL到控制台并获取undefined.

为什么运行时不跟踪我的环境变量?

.env

NUXT_PUBLIC_BASE_URL=https://example.com/api/v1
Run Code Online (Sandbox Code Playgroud)

nuxt.config.js

export default defineNuxtConfig({
  runtimeConfig: {
    public: {
      baseUrl: ''
    }
  },
Run Code Online (Sandbox Code Playgroud)

插件/app.js

NUXT_PUBLIC_BASE_URL=https://example.com/api/v1
Run Code Online (Sandbox Code Playgroud)

kis*_*ssu 1

文档页面

但是,在构建服务器后,您需要负责在运行服务器时设置环境变量。此时将不会读取您的 .env 文件。对于每个环境,执行此操作的方式都不同。在 Linux 服务器上,您可以使用终端 DATABASE_HOST=mydatabaseconnectionstring node .output/server/index.mjs 将环境变量作为参数传递。或者您可以使用 source .env && node .output/server/index.mjs 获取 env 文件。请注意,对于纯静态站点,在项目预渲染后无法设置运行时配置。

所以,source .env && yarn start应该这样做。