Catch the role of Environment Variables in Vue JS
When we are developing an application, we always have different application settings based on the development stages or environment we are in. Environments will be like development, staging, alpha, beta, production, etc.,
In this article, we will understand how to provide different settings based on the environment in the Vue application created with Vue CLI.
In case, you do not have a Vue project ready with you. Follow the next two steps to create a new Vue project with me.
Install Vue CLI
|
|
Create Project
Run below command and select the preset as per your requirement, Vue CLI will setup necessary files to start development.
|
|
It will take a couple of minutes to install the dependencies, once it is done navigation to the generated directory (in our case vue-project
) and run below command to start local server.
|
|
Default Environment Variable
We are all set with our initial project setup. In Vue app, the whole environment settings object will be available at process.env
.
Replace App.vue
with below code:
Here is the first look of default env variables:
Learned: All environment variables can be accessible from process.env object
Custom Environment Variable
Where do we need custom environment variables? As we discussed earlier in the article, we have different stages in the development process. For example, in every stage, we will not be using the same API. Here, the base endpoint URL can be added as one custom environment variable.
Similarly based on your requirement you can add how many ever custom variables you want.
Where do we add custom environment variables? All the variables should be added in .env
file.
|
|
For example: If you want to give settings for the development environment, you can replace mode
with development
. Similarly for staging, production, etc.,
|
|
How to write environment variables in env file? Environment variables should be written in key-value pairs as shown in the below example and all the custom variables must start with VUE_APP_
. Otherwise, your variable will not available under process.env
Example (.env.development):
|
|
Example (.env.production):
|
|
Learned: All custom variables must start with
VUE_APP_
Run/Build in different ENV modes
How to run in different environments? If you have to run or build a Vue app in different environments, you must specify value for --mode
key while running command like in the below examples. By default, development is mode for running and production is the mode for building.
Command to run your Vue application:
|
|
Command to build your Vue application:
|
|
Command with options:
|
|
Here is the difference between different stages:
Tweek & try yourself with this sample repository.
References
Conclusion
If we utilize well, environment variables will play a key role in the development process. I hope you like this article. If you have any queries please comment below.