Search code examples
htmlvue.jstemplatesenvironment-variables

access vue environment variables in template


I want to access my environment variables from the template of vue single file components however, doing the following:

<img :src="`${process.env.VUE_APP_API_BASE_URL}/image/${image.filename}`" alt="" />

gives me the error:

 Property or method "process" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property

i know my environment variables are set up correctly as i can use them in other places, and i can use a workaround to create a new variable on the component and reference that:

data() {
  return {
    BaseUrl: process.env.VUE_APP_API_BASE_URL,
  };
},

<img :src="`${BaseUrl}/image/${image.filename}`" alt="" />

and that is able to load the image correctly, but how can i access the env variables directly in the template without the need to initialise a new variable for each component?


Solution

  • process.env environment variables are replaced with actual values at compilation time. The error means that this doesn't happen in templates.

    Things can be defined globally for all components, e.g. for Vue 2:

    Vue.prototype.$baseUrl = process.env.VUE_APP_API_BASE_URL;
    

    Putting too much code into templates is a bad practice. In this case image URL can be defined as computed, or as method for image provided by v-for.