Pierre Burton
Pierre Burton

Reputation: 2084

How to access env variable in functional component?

I would like to define a default value if a prop is not passed to my functional component. This default value is an environement variable.

When I try the following, compilation will throw an error TypeError: Cannot read property 'env' of undefined

<template functional>
    <div class="header__small">{{ props.header_small ? props.header_small : process.env.VUE_APP_DEFAULTHEADER }}</div>
</template>

The same happens if I try with parent.process.env.VUE_APP_DEFAULTHEADER

The env variable are working fine in every other classic component accross the app. It just won't work with functional ones. Ternary operator to define a default value works well also if I pass it any other value, just not process.env.

Upvotes: 1

Views: 1332

Answers (1)

Michal Lev&#253;
Michal Lev&#253;

Reputation: 37753

As you are using it only as default value for a prop, did you try this?

props: {
  header_small: {
    type: String,
    default: process.env.VUE_APP_DEFAULTHEADER
  }
}
  1. process.env.XXX cannot be used in template directly - applies to statefull and functional components alike
  2. It must always be used in the <script> part of the component
  3. In functional components, only places it can be used is as default value of prop declaration or directly in render() function code

More details

In Webpack/Vue CLI projects, environment variables are handled by Webpack DefinePlugin. It replaces any occurrence of process.env.XXX by some string value defined in .env files. This happens at build time.

For some reason it works only when used inside <script> part of SFC's (JS most of the time). But we know that Vue templates are compiled into plain JavaScript too. So why is it it doesn't work also in the template ? I was trying to google a bit but didn't found any answer. So I guess it was a decision of vue-loader creators to not allow DefinePlugin to process the output of the Vue compiler maybe because its nature (essentially string replacement) and fear of hard to debug/support issues...

Upvotes: 1

Related Questions