Using Environment Variables with Vue.js
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=valueVUE_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.
If you are using Vue cli 3, only variables that start with VUE_APP_ will be loaded.
In the root create a .env file with:
VUE_APP_ENV_VARIABLE=value
And, if it's running, you need to restart serve so that the new env vars can be loaded.
With this, you will be able to use process.env.VUE_APP_ENV_VARIABLE in your project (.js and .vue files).
Update
According to @ali6p, with Vue Cli 3, isn't necessary to install dotenv dependency.
- Create two files in root folder (near by package.json)
.env
and.env.production
- Add variables to theese files with prefix
VUE_APP_
eg:VUE_APP_WHATEVERYOUWANT
- serve uses
.env
and build uses.env.production
- In your components (vue or js), use
process.env.VUE_APP_WHATEVERYOUWANT
to call value - Don't forget to restart serve if it is currently running
- Clear browser cache
Be sure you are using vue-cli version 3 or above
For more information: https://cli.vuejs.org/guide/mode-and-env.html