nuxt-community / dotenv-module

Loads your .env file into your application context
MIT License
495 stars 30 forks source link

variables not defined on init #2

Closed javialon26 closed 7 years ago

javialon26 commented 7 years ago

the environment variables are not defined at the beginning. I am using the nuxtjs / axios module where I configure:

baseURL: process.env.API_URL,
browserBaseURL: process.env.API_URL_BROWSER

with this config an error occurs:

TypeError: Cannot read property 'substr' of undefined
    at ModuleContainer.nuxtAxios (/home/javier/vms/twobvm/projects/cominghouse/node_modules/@nuxtjs/axios/lib/index.js:38:46)

thank you!

This question is available on Nuxt.js community (#c2)
JulienTant commented 7 years ago

Hi,

The dotenv-module won't overload the environment variables of the process running your build.

If you need to use variables from your .env file at this moment (and it looks like you do), just append require('dotenv').config() to your nuxt.config.js :

require('dotenv').config()

module.exports = {
    // your usual nuxt config.
}

This will works thanks to the dotenv library provided by this module as a dependency. If you decided to ignore some values from your .env file in the module configuration, this won't apply here.

Hope this help, i will update the README file with this, it can be useful !

KnutSv commented 6 years ago

Not sure what I'm doing wrong, but I can't seem to access the process.env-variable no matter what I do.

process.env

API_BASE_URL=http://api.test.com

nuxt.config.js

require('dotenv').config()

module.exports = {
  ...
  mode: 'spa',
  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/dotenv',
  ],
  axios: {
    proxy: true
  },
  proxy: {
    '/api/': process.env.API_BASE_URL
  }
}

In this setup process.env.API_BASE_URL is always: undefined

willbrowningme commented 6 years ago

@KnutSv what do you get if you console.log(process.env) just above module.exports?

If your setup above isn't working you can try the following:

// nuxt.config.js
const env = require('dotenv').config().parsed

module.exports = {
  ...
  mode: 'spa',
  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/dotenv',
  ],
  axios: {
    proxy: true
  },
  proxy: {
    '/api/': env.API_BASE_URL
  }
}
KnutSv commented 6 years ago

@willbrowningme Seems my problem was mainly that i named my .env-file process.env for some reason. Guess I got it mixed up when reading the doc. When I renamed it i and assigned it to a variable like you suggested (though i didn't need the .parsed part) it worked perfectly. Thanks :-)