简体   繁体   English

如何在 Vue.js 中使用 dotenv

[英]How to use dotenv with Vue.js

I'm trying to add some environment variables into my vue app.我正在尝试将一些环境变量添加到我的 vue 应用程序中。

here is content of my .env file, which is placed on root(outside src ):这是我的.env文件的内容,它位于根目录(外部src ):

VUE_APP_GOODREADS_KEY = my_key

and I added code for dot env on the top of my main.js我在main.js的顶部添加了 dot env 的代码

import Vue from 'vue'
import App from './App'
import VueResource from 'vue-resource'
import Vuetify from 'vuetify'

import dotenv from 'dotenv'

dotenv.config()

import { router } from './router'
import store from './store'

I want to use this variable within my store ./store/index.js我想在我的商店./store/index.js使用这个变量

I tried to console.log environment variables within store but no luck:我试图在商店中 console.log 环境变量,但没有运气:

console.log(process.env)

But all I'm getting is但我得到的只是

NODE_ENV:"development"

Only related thread I found was Load environment variables into vue.js , but it only mentions how to use existing variables in the process.env .我发现的唯一相关线程是将环境变量加载到 vue.js 中,但它只提到了如何使用process.env现有变量。 I want to add environment variables using dotenv.我想使用 dotenv 添加环境变量。 Why this code is not working?为什么这段代码不起作用?

If your project was create by using Vue CLI 3 , no need to use dotenv to get environment variables.如果您的项目是使用Vue CLI 3创建的,则无需使用dotenv来获取环境变量。

To get environment variables within .env file in your project:要在项目中的.env文件中获取环境变量:

  1. Placing the .env file in your project root..env文件放在您的项目根目录中。
  2. In the .env file, specifying environment variables with "VUE_APP_" prefix..env文件中,指定带有“VUE_APP_”前缀的环境变量。

    VUE_APP_SOMEKEY=SOME_KEY_VALUE . VUE_APP_SOMEKEY=SOME_KEY_VALUE

  3. Finally, you can access them with process.env.* in your application code.最后,您可以在应用程序代码中使用process.env.*访问它们。

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

Referance: Vue CLI 3 - Environment Variables and Modes参考: Vue CLI 3 - 环境变量和模式

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 时,您必须使用位于 config 文件夹中的 dev.env.js 和 prod.env.js 文件。

Vue CLI 2 does not support the use of .env files, however Vue CLI 3 does . Vue CLI 2 不支持使用 .env 文件,但Vue CLI 3 支持

// /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"
}

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参考: https : //github.com/motdotla/dotenv#config

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

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