问题描述
我一直在阅读官方文档,但无法找到有关环境变量的任何信息.显然,有一些社区项目支持环境变量,但这对我来说可能是过大了.因此,我想知道在使用Vue CLI创建的项目上是否有一些简单的开箱即用的功能可以正常工作?
I've been reading the official docs and I'm unable to find anything on environment variables. Apparently there are some community projects that support environment variables but this might be overkill for me. So I was wondering if there's something simple out of the box that works natively when working on a project already created with Vue CLI.
例如,我可以看到,如果执行以下操作,将打印出正确的环境,这意味着已经设置好了?
For example, I can see that if I do the following the right environment prints out meaning this is already setup?
mounted() {
console.log(process.env.ROOT_API)
}
我有点喜欢env变量和Node.
I'm a kinda new to env variables and Node.
FYI使用Vue CLI 3.0 beta版.
FYI using Vue CLI version 3.0 beta.
推荐答案
如果将vue cli与Webpack模板一起使用(默认配置),则可以创建环境变量并将其添加到.env文件.
If you use vue cli with the Webpack template (default config), you can create and add your environment variables to a .env file.
将在项目的process.env.variableName
下自动访问变量.加载的变量也可用于所有vue-cli-service命令,插件和依赖项.
The variables will automatically be accessible under process.env.variableName
in your project. Loaded variables are also available to all vue-cli-service commands, plugins and dependencies.
您有一些选择,来自环境变量和模式文档:
.env # loaded in all cases
.env.local # loaded in all cases, ignored by git
.env.[mode] # only loaded in specified mode
.env.[mode].local # only loaded in specified mode, ignored by git
您的.env文件应如下所示:
Your .env file should look like this:
VUE_APP_MY_ENV_VARIABLE=value
VUE_APP_ANOTHER_VARIABLE=value
据我了解,您需要做的就是创建.env文件并添加变量,然后就可以开始了! :)
It is my understanding that all you need to do is create the .env file and add your variables then you're ready to go! :)
如以下评论所述:如果您使用的是Vue cli 3,则只会加载以 VUE_APP _ 开头的变量.
As noted in comment below:If you are using Vue cli 3, only variables that start with VUE_APP_ will be loaded.
如果 serve 当前正在运行,请不要忘记重新启动它.
Don't forget to restart serve if it is currently running.
这篇关于在Vue.js中使用环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!