简体   繁体   English

如何在 Nuxt 2 或 3 中使用 .env 变量?

[英]How to use .env variables in Nuxt 2 or 3?

I have.env file in the project root, and in my nuxt config I am using variables to configure ReCaptcha like this:我在项目根目录中有 .env 文件,在我的 nuxt 配置中,我使用变量来配置 ReCaptcha,如下所示:

import dotenv from 'dotenv'
dotenv.config()

export default {
    modules: [
        ['@nuxtjs/recaptcha', {
          siteKey: process.env.RECAPTCHA_SITE_KEY,
          version: 3,
          size: 'compact'
        }],
    ]
}

and in.env like this:和 in.env 是这样的:

RECAPTCHA_SITE_KEY=6L....

but the application always failed with console log error:但应用程序总是因控制台日志错误而失败:

ReCaptcha error: No key provided ReCaptcha 错误:未提供密钥

When I hard-code ReCaptcha key directly like that: siteKey: 6L.... app start working, so I guess the problem is with reading.env props in nuxt.config当我像这样直接硬编码 ReCaptcha 密钥时: siteKey: 6L.... app 开始工作,所以我猜问题出在 nuxt.config 中的 reading.env props

do you have any idea how to fix it?你知道如何解决吗?

EDIT: I tried update my nuxt.config by @kissu recommendation and by example which I found here: https://www.npmjs.com/package/@nuxtjs/recaptcha编辑:我尝试通过@kissu 推荐和我在这里找到的示例更新我的 nuxt.config: https://www.npmjs.com/package/@nuxtjs/recaptcha

so there is new nuxt.config which also not working:所以有新的 nuxt.config 也不起作用:

export default {
    modules: [
       '@nuxtjs/recaptcha',
    ],
    publicRuntimeConfig: {
       recaptcha: {
         siteKey: process.env.RECAPTCHA_SITE_KEY,
         version: 3,
         size: 'compact'
       }
  }
}

If your Nuxt version is 2.13 or above , you don't need to use @nuxtjs/dotenv or anything alike because it is already backed into the framework.如果您的 Nuxt 版本是2.13 或更高版本,则不需要使用@nuxtjs/dotenv或类似的东西,因为它已经支持到框架中。

To use some variables, you need to have an .env file at the root of your project.要使用一些变量,您需要在项目的根目录下有一个.env文件。 This one should be ignored by git. git 应该忽略这一点。 You can then input some keys there like然后你可以在那里输入一些键,比如

PUBLIC_VARIABLE="https://my-cool-website.com"
PRIVATE_TOKEN="1234qwer"

In your nuxt.config.js , you have to input those into 2 objects, depending of your use case, either publicRuntimeConfig or privateRuntimeConfig :在您的nuxt.config.js中,您必须将它们输入到 2 个对象中,具体取决于您的用例, publicRuntimeConfigprivateRuntimeConfig

export default {
  publicRuntimeConfig: {
    myPublicVariable: process.env.PUBLIC_VARIABLE,
  },
  privateRuntimeConfig: {
    myPrivateToken: process.env.PRIVATE_TOKEN
  }
}

Differences : publicRuntimeConfig can basically be used anywhere, while privateRuntimeConfig can only be used during SSR (a key can only stay private if not shipped to the browser).区别publicRuntimeConfig基本上可以在任何地方使用,而privateRuntimeConfig只能在 SSR 期间使用(如果没有发送到浏览器,密钥只能保持私有)。

A popular use case for the privateRuntimeConfig is to use it for nuxtServerInit or during the build process (either yarn build or yarn generate ) to populate the app with headless CMS' API calls. privateRuntimeConfig的一个流行用例是将其用于nuxtServerInit或在构建过程( yarn buildyarn generate )以使用无头 CMS 的 API 调用填充应用程序。

More info can be found on this blog post: https://nuxtjs.org/blog/moving-from-nuxtjs-dotenv-to-runtime-config/更多信息可以在这篇博客文章中找到: https://nuxtjs.org/blog/moving-from-nuxtjs-dotenv-to-runtime-config/


  • Then, you will be able to access it into any .vue file directly with然后,您将能够直接将其访问到任何.vue文件中
this.$config.myPublicVariable
  • You access it into Nuxt's /plugins too, with this syntax您也可以使用此语法将其访问到 Nuxt 的/plugins
export default ({ $axios, $config: { myPublicVariable } }) => {
  $axios.defaults.baseURL = myPublicVariable
}
  • If you need this variable for a Nuxt module, write it directly with如果 Nuxt 模块需要这个变量,直接用
process.env.PRIVATE_TOKEN

Sometimes, the syntax may differ a bit , in this case refer to your Nuxt module documentation.有时,语法可能会有所不同,在这种情况下,请参阅您的 Nuxt 模块文档。

// for @nuxtjs/gtm
publicRuntimeConfig: {
  gtm: {
    id: process.env.GOOGLE_TAG_MANAGER_ID
  }
},

PS: if you do use target: server (default value), you can yarn build and yarn start to deploy your app to production. PS:如果你使用target: server (默认值),你可以使用yarn buildyarn start将你的应用部署到生产环境。 Then, change any environment variables that you'd like and yarn start again.然后,更改您想要的任何环境变量并yarn start There will be no need for a rebuild.将不需要重建。 Hence the name RuntimeConfig !因此名称RuntimeConfig

It's very easy.这很容易。 Providing you an example with axios/nuxt为您提供 axios/nuxt 的示例

  1. Define your variable in the .env file:.env文件中定义变量:

    baseUrl=http://localhost:1337

  2. Add the variable in the nuxt.config.js in an env-object (and use it in the axios config):在环境对象的 nuxt.config.js 中添加变量(并在 axios 配置中使用它):

    export default {env: {baseUrl: process.env.baseUrl},axios: {baseURL: process.env.baseUrl},}

  3. Use the env variable in any file like so:在任何文件中使用 env 变量,如下所示:

    console.log(process.env.baseUrl)

Note that console.log(process.env) will output {} but console.log(process.env.baseUrl) will still output your value!请注意console.log(process.env)将 output {} 但console.log(process.env.baseUrl)仍将 output 您的价值!

You can also use the env property with Nuxt nuxt.config.js:您还可以将env属性与 Nuxt nuxt.config.js 一起使用:

export default {
  // Environment variables
  env: {
    myVariable: process.env.NUXT_ENV_MY_VAR
  },
  ...
}

Then in your plugin:然后在你的插件中:

const myVar = process.env.myVariable

For nuxt3 rc11, in nuxt.conf.ts file:对于 nuxt3 rc11,在 nuxt.conf.ts 文件中:

export default defineNuxtConfig({
  runtimeConfig: {
    public: {
      locale: {
        defaultLocale: process.env.NUXT_I18N_LOCALE,
        fallbackLocale: process.env.NUXT_I18N_FALLBACK_LOCALE,
      }
    }
  },
...

and in.env file:和 in.env 文件:

NUXT_I18N_LOCALE=tr
NUXT_I18N_FALLBACK_LOCALE=en

public: is very important otherwise it cannot read it and gives undefined error. public: 非常重要,否则它无法读取它并给出未定义的错误。

For v3 there is a precise description in the official docs对于 v3, 官方文档中有准确的描述

You define a runtimeConfig entry in your nuxt.config.[ts,js] which works as initial / default value:您在nuxt.config.[ts,js]中定义一个 runtimeConfig 条目,它用作初始值/默认值:

export default defineNuxtConfig({
  runtimeConfig: {
    recaptchaSiteKey: 'default value' // This key is "private" and will only be available within server-side
  }
}

You can also use env vars to init the runtimeConfig but its written static after build.您还可以使用 env vars 来初始化 runtimeConfig,但它在构建后写入 static But you can override the value at runtime by using the following env var:但是您可以使用以下环境变量在运行时覆盖该值:

NUXT_RECAPTCHA_SITE_KEY=SOMETHING DYNAMIC

If you need to use the config on client-side, you need to use the public property.如果您需要在客户端使用配置,则需要使用公共属性。

export default defineNuxtConfig({
  runtimeConfig: {
    public: {
      recaptchaSiteKey: 'default value' // will be also exposed to the client-side
    }
  }
}

Notice the PUBLIC part in the env var:注意环境变量中的PUBLIC部分:

NUXT_PUBLIC_RECAPTCHA_SITE_KEY=SOMETHING DYNAMIC

This is very strange because we can't access process.env in Nuxt 3这很奇怪,因为我们无法在 Nuxt 3 中访问process.env

In the Nuxt 3, we are invited to use the runtime config, but this is not always convenient, because the Nuxt application context is required.在 Nuxt 3 中,我们被邀请使用运行时配置,但这并不总是很方便,因为需要 Nuxt 应用程序上下文。

But in a situation where we have some plain library, and we don't want to wrap it in plugins nor composables functions, declaring global variables through vite / webpack is best:但是在我们有一些普通库的情况下,我们不想将它包装在插件或可组合函数中,最好通过 vite / webpack 声明全局变量:

// nuxt.config.ts
export default defineNuxtConfig({
  vite: {
    define: {
      MY_API_URL: JSON.stringify(process.env.MY_API_URL)
    }
  }
})

And then you can use in any file without dancing with a tambourine:然后你可以在任何文件中使用而不用手鼓跳舞:

// some-file.ts
console.log('global var:', MY_API_URL) // replaced by vite/webpack in real value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM