Env 变量在 Nuxt 应用程序中不可用

Env variable is not available within Nuxt app

按照文档 (here and here),我已经这样设置了我的 .env 变量 IFRAME_CHECKER

.env:

IFRAME_CHECKER=https://path.to.some.script

nuxt.config.js:

publicRuntimeConfig: {
  axios: {
    baseURL: process.env.BASE_URL
  },
  iframeChecker: process.env.IFRAME_CHECKER
}

然而在我的组件中(例如在 mounted() 钩子中),this.$config.iframeChecker returns null。为什么?

重新安装@nuxt/dotenv

.env

IFRAME_CHECKER=https://path.to.some.script

在你的 nuxt.config.js:

export default {
  publicRuntimeConfig: {
  axios: {
    baseURL: process.env.BASE_URL
  },
    iframeChecker: process.env.IFRAME_CHECKER
  }
}

可以这样访问

this.$config.IFRAME_CHECKER

我无法重现你的问题。

注意:您不需要@nuxtjs/dotenv包。

我得到它与以下工作:

nuxt.config.js

export default {
  publicRuntimeConfig: {
    iframeChecker: process.env.IFRAME_CHECKER || 'https://nuxtjs.org'
  },
  ...
}

.env

IFRAME_CHECKER=http://test

iframeChecker 应该像这样可用:

mycomponent.vue

export default {
  ...
  mounted() {
    console.log(this.$config.iframeChecker)
  }
  ...
}