在 Vue.js 中使用环境变量 [英] Using Environment Variables with Vue.js

查看:30
本文介绍了在 Vue.js 中使用环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读官方文档,但找不到有关环境变量的任何信息.显然有一些社区项目支持环境变量,但这对我来说可能有点矫枉过正.所以我想知道在处理已经使用 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.

仅供参考,使用 Vue CLI 3.0 测试版.

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.

您有几个选项,这来自环境变量和模式文档:

You have a few options, this is from the Environment Variables and Modes documentation:

.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 中使用环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆