How to use dotenv with Vue.js

前端 未结 3 1196
无人及你
无人及你 2021-02-19 01:43

I\'m trying to add some environment variables into my vue app.

here is content of my .env file, which is placed on root(outside src):



        
相关标签:
3条回答
  • 2021-02-19 02:04

    Try removing the spaces around the equal sign.

    VUE_APP_GOODREADS_KEY=my_key
    

    Also, try debugging like this:

    const config = dotenv.config()
    if(config.error){
      console.log('Could not load env file', config.error)
    }
    

    Reference: https://github.com/motdotla/dotenv#config

    0 讨论(0)
  • 2021-02-19 02:09

    If your project was create by using Vue CLI 3, no need to use dotenv to get environment variables.

    To get environment variables within .env file in your project:

    1. Placing the .env file in your project root.
    2. In the .env file, specifying environment variables with "VUE_APP_" prefix.

      VUE_APP_SOMEKEY=SOME_KEY_VALUE.

    3. Finally, you can access them with process.env.* in your application code.

      console.log(process.env.VUE_APP_SOMEKEY) // SOME_KEY_VALUE

    Referance: Vue CLI 3 - Environment Variables and Modes

    0 讨论(0)
  • 2021-02-19 02:18

    When using Vue CLI 2, you have to use the dev.env.js and prod.env.js files located in the config folder.

    Vue CLI 2 does not support the use of .env files, however Vue CLI 3 does.

    // /config/prod.env.js
    'use strict'
    module.exports = {
      NODE_ENV: '"production"',
      SERVER_URI: "http://someremoteuri:3333/api/v1"
    }
    
    // /config/dev.env.js
    'use strict'
    module.exports = {
      NODE_ENV: '"development"',
      SERVER_URI: "http://localhost:3333/api/v1"
    }
    
    0 讨论(0)
提交回复
热议问题