1

I have a pretty standard component that imports and uses other components. I want to conditionally import one of its child components based on a value set in my .env file, but it doesn't seem like either process.env or this is accessible outside the export default {} script object.

So I'd like to find out how I can access values set in my .env file from here, if it's even possible?

Here's a recreation of what I'm trying to do:

my-component.vue

<template>
  <!-- irrelevant markup -->
</template>

<script>
  import ChildComp from process.env.VAL === 'thing' ? '@/components/child1' : '@/components/child2';
  // or even ` ... from this.$config.VAL === ... `

  export default {
    components: { ChildComp },

    // more irrelevant code here...
  }
</script>

So that pretty much shows what I'm trying to do. I know that the nuxt way of doing env vals is by declaring them in the publicRuntimeConfig and privateRuntimeConfig objects in nuxt.config.js, so that's what I've done, and now my .VAL is accessible in my component through this.$config.VAL - just not outside export default {} -_-

Any thoughts or ideas will be appreciated. And let me know if you need more to go on.

kissu
  • 40,416
  • 14
  • 65
  • 133
SeriousLee
  • 1,301
  • 4
  • 20
  • 42
  • Does this answer your question? [How to use .env variables in Nuxt 2 or 3?](https://stackoverflow.com/questions/67703133/how-to-use-env-variables-in-nuxt-2-or-3) – kissu Oct 27 '21 at 10:16
  • Please give a read to this article too: https://nuxtjs.org/tutorials/moving-from-nuxtjs-dotenv-to-runtime-config – kissu Oct 27 '21 at 10:17

1 Answers1

-1

In Nuxt you have no access to your .env vars by default as the Nuxt App can also be served without any server.

So you need to add your env-vars to the nuxt config in order to access them.

export default {
  env: {
    baseUrl: process.env.BASE_URL || 'http://localhost:3000'
  }
}

In the app, you can access them like

  • process.env.baseUrl
  • context.env.baseUrl
thopaw
  • 3,796
  • 2
  • 17
  • 24
  • I'm not sure that this is the way to go looking at this page of the documentation: https://nuxtjs.org/docs/configuration-glossary/configuration-env#the-env-property – kissu Oct 27 '21 at 10:18