如何在 Vue.js 中使用 dotenv [英] How to use dotenv with Vue.js
问题描述
我正在尝试将一些环境变量添加到我的 vue 应用程序中.
I'm trying to add some environment variables into my vue app.
这里是我的 .env
文件的内容,它被放置在 root(outside src
) 上:
here is content of my .env
file, which is placed on root(outside src
):
VUE_APP_GOODREADS_KEY = my_key
并且我在 main.js
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'
我想在我的商店中使用这个变量 ./store/index.js
I want to use this variable within my store ./store/index.js
我尝试在 store 中 console.log 环境变量,但没有成功:
I tried to console.log environment variables within store but no luck:
console.log(process.env)
但我得到的只是
NODE_ENV:"development"
我发现的唯一相关线程是将环境变量加载到 vue.js,但它只提到如何使用 process.env
中的现有变量.我想使用 dotenv 添加环境变量.为什么此代码不起作用?
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
. I want to add environment variables using dotenv. Why this code is not working?
推荐答案
如果你的项目是使用 Vue CLI 3
创建的,不需要使用 dotenv
来获取环境变量.
If your project was create by using Vue CLI 3
, no need to use dotenv
to get environment variables.
要在项目的 .env
文件中获取环境变量:
To get environment variables within .env
file in your project:
- 将
.env
文件放在项目根目录中. 在
.env
文件中,指定带有VUE_APP_"前缀的环境变量.
- Placing the
.env
file in your project root. In the
.env
file, specifying environment variables with "VUE_APP_" prefix.
VUE_APP_SOMEKEY=SOME_KEY_VALUE
.
最后,您可以在应用程序代码中使用 process.env.*
访问它们.
Finally, you can access them with process.env.*
in your application code.
console.log(process.env.VUE_APP_SOMEKEY)//SOME_KEY_VALUE
这篇关于如何在 Vue.js 中使用 dotenv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!