Using Environment Variables with Vue.js

Edgar Quintero picture Edgar Quintero · Jun 13, 2018 · Viewed 110k times · Source

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)
}

I'm a kinda new to env variables and Node.

FYI using Vue CLI version 3.0 beta.

Answer

RAH picture RAH · Jun 13, 2018

If you use vue cli with the Webpack template (default config), you can create and add your environment variables to a .env file.

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

Your .env file should look like this:

VUE_APP_MY_ENV_VARIABLE=value
VUE_APP_ANOTHER_VARIABLE=value

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! :)

As noted in comment below: If you are using Vue cli 3, only variables that start with VUE_APP_ will be loaded.

Don't forget to restart serve if it is currently running.