1

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.

Pierre Burton
  • 1,954
  • 2
  • 13
  • 27
  • 2
    I know this will sound like a cliche StackOverflow answer, but functional components are made just for that reason alose, _to be stateless_. The reason how you make `process` variable work is define it inside `data`, `computed` or return it in `methods`, which are not present inside functional components, _to be stateless_. – ColdHands Sep 17 '20 at 08:05
  • That's actually a pretty good answer. I didn't think I could not access process directly in any template, you can only use them in the script part of component. Well that's a shame. Please, post it as an answer so I can mark you as accepted answer ! – Pierre Burton Sep 17 '20 at 09:19

1 Answers1

1

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...

Michal Levý
  • 33,064
  • 4
  • 68
  • 86
  • Oh well this is even better ! I didn't know the script would be interpreted by the compiler once the SFC is set as functional. Great ! Thank you ! – Pierre Burton Sep 17 '20 at 10:20