Have an app that's built in Vue. Been trying to figure this out for a while. Im unable to access process variables. Have tried multiple things so far.
Im using vue/cli 4.3.1 What am i missing?
[Edits]
Right now, my .env has only 1 entry
Trying to access it in the created() method
created: function() { console.log(process.env.VUE_APP_NOT_SECRET_CODE); }
Here is my folder structure
process
is undefined
You might want to update your NodeJs Version (and npm), remove the node_modules
folder and hit npm install
again. I read a few cases where this helped.
env
fileThe .env
file might be faulty in some way. Try deleting the file and re-creating it using console (like touch .env
on linux)
undefined
VUE_APP_MYVAR
instead of MYVAR
The most common error when it comes to Environment Variables
inside Vue
is the naming. When using env
you have to prefix all variables with VUE_APP_
, otherwise Vue won't include them.
More background info here : https://cli.vuejs.org/guide/mode-and-env.html. From the docs
Note that only NODE_ENV, BASE_URL, and variables that start with VUE_APP_ will be statically embedded into the client bundle with webpack.DefinePlugin. It is to avoid accidentally exposing a private key on the machine that could have the same name.
🚧 Make sure to not include any secrets (such as private API keys) in your app! Environment variables are embedded into the build, meaning anyone can view them by inspecting your app's files.
While the other answers might be helpful, the eventual solution to this problem for me was, to actually only read the values at mounted
. I am unsure why exactly, but this worked for me:
mounted: function (): void {
console.log('App version: ' + process.env.VUE_APP_VERSION);
console.log('Environment: ' + process.env.NODE_ENV);
},
For showing them in the templated HTML output, I had to make sure, that undefined
did not crash the process, and I have done it (the ugly way) like this (note the extra empty strings at the beginning in the computed functions):
<p title="App info">
<small>App version: {{ version }} ({{ environment }})</small>
</p>
//....
computed: {
version(): string {
return '' + process.env.VUE_APP_VERSION;
},
environment(): string {
return '' + process?.env?.NODE_ENV;
},
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With