Reputation: 2084
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
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
}
}
process.env.XXX
cannot be used in template directly - applies to statefull and functional components alike<script>
part of the componentdefault
value of prop
declaration or directly in render()
function codeIn 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