Home » vue » When I use env files I got undefined when I read the vars

When I use env files I got undefined when I read the vars

Posted by: admin November 26, 2021 Leave a comment

Questions:

I created a Vue application using vue/cli: vue create my-vue. I want to build this project in next mode (like qa, stage, next …), so I followed the steps in the Vue docs. I created the .env.next file in the root project with this content:

FOO=next

In my main.js, I log it to the console:

import Vue from 'vue'
import App from './App.vue'

console.log({ f: process.env.FOO }); // <----- undefined. why?
console.log({ f: process.env.VUE_APP_FOO }); // <----- undefined. why?

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')

After that, I run the build:

npm run build -- --mode next

When I run the dist folder in the console, I get undefined. I searched for "next" in the bundle, but it’s not there.

Why? How can I use .env vars in my build output?

Answers:

As stated in the docs you’ve linked:

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.

For FOO to be available in the build output, rename it to VUE_APP_FOO in your .env file, and update references accordingly:

console.log({ f: process.env.VUE_APP_FOO })