Accessing Env Variables via Instance Properties in Vue 2
I'm extracting a legacy Vue app from a .NET monorepo into its own standalone repo. One of the first challenges: how to handle environment variables that were previously injected by .NET once Vue was decoupled.
After some digging around the docs, I decided to solve this by storing these variables in a standard .env and attaching them to the Vue instance through its prototype - also known as Instance Properties. Specifically, I added them as an object under the property $config.
Here is what creating and attaching that object looks like:
// config.js
const config = {
// Pull values from env
appName: process.env.APP_NAME,
baseUrl: process.env.BASE_URL,
clientId: process.env.CLIENT_ID,
};
export default {
install(Vue) {
// Here is where we attach the object to Vue
Vue.prototype.$config = config;
}
};
// Export config object for use in common JS files
export { config };
// main.js
import Vue from "vue";
import config from "@/plugins/config.js";
Vue.use(config);
new Vue({
...
}).$mount("#app");Once attached, our env variables are accessible from any component:
this.$config.appName // Vue2 AppOr they can be added directly into templates:
<h1>{{ $config.appName }}</h1>A unique situation for my use case was I also needed to export my config object as I also needed these variables available to a few common JS modules that are being used in the application. Exporting the config object allows me to import it and access our variables.
// service.js
import { config } from "../path/to/config.js";
...
const clientId = config.clientId;This provides a clean and centralized configuration that is accessible by both Vue and common JS file. Sure, it may add more boilerplate compared to throwing process.env throughout the code, but I feel this approach simply improves maintainability and readability.