首頁  >  文章  >  web前端  >  為什麼我的 .env 變數在我的 Nuxt 應用程式中不起作用?

為什麼我的 .env 變數在我的 Nuxt 應用程式中不起作用?

Patricia Arquette
Patricia Arquette原創
2024-11-15 05:44:03237瀏覽

Why is My .env Variable Not Working in My Nuxt Application?

Troubleshooting .env Variables in Nuxt 2 and 3

Problem Statement

Nuxt applications may encounter an error when using .env variables to configure modules, such as ReCaptcha. The console may display "ReCaptcha error: No key provided," despite the presence of an .env file with the required key.

Explanation

In Nuxt 2.13 and above, the @nuxtjs/dotenv module is no longer necessary as runtime configuration is built into the framework. To utilize .env variables, follow these steps:

Nuxt 2.13+

  • Create an .env file at the project root.
  • Import the necessary variables into nuxt.config.js:

    export default {
    publicRuntimeConfig: {
      recaptcha: {
        siteKey: process.env.RECAPTCHA_SITE_KEY,
        version: 3,
        size: 'compact'
      }
    }
    }
  • Use the variables in your components using this.$config.

Nuxt 3

  • Import the following:

    import { defineNuxtConfig } from 'nuxt3'
  • Use the following in nuxt.config.js:

    export default defineNuxtConfig({
    runtimeConfig: {
      public: {
        secret: process.env.SECRET,
      }
    }
    }
  • Use the variables in your components using useRuntimeConfig():

    <script setup lang="ts">
    const config = useRuntimeConfig()
    config.secret
    </script>
  • Use the variables in composables:

    export default () => {
    const config = useRuntimeConfig()
    console.log(config.secret)
    }

Nuxt 2 Pre-2.13

If using Nuxt 2 pre-2.13, the @nuxtjs/dotenv module is required. You can add this method to your nuxt.config.js file:

import dotenv from 'dotenv'
dotenv.config()

以上是為什麼我的 .env 變數在我的 Nuxt 應用程式中不起作用?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn