Vue-cli 3 Environment Variables all undefined
A few tips for people who land here:
- Make sure your
.env
files are in the project root folder (and not in saysrc/
) - Variable names should start with
VUE_APP_
if to be statically embedded into the client bundle - Restart the dev server or build your project for changes to take effect
- If you are migrating from a webpack based solution make sure that you replace
:
(from JSON config) with=
(dotenv format). Easy to miss - Make sure you've saved any changes to your
.env
files. - In old Vue versions environment variables were defined in e.g.
config/dev.env.js
instead of the.env
files in root
I figured it out - I had to install dotenv-webpack
and initialize it in webpack.config.js which is odd because none of the docs stated that I needed to do so.
so I use VUE_APP_API_URL (this doesn't work) then I change it to VUE_APP_APIURL (this works)
hope it helps
Install dotenv-webpack
and configure the vue.config.js
file as follows.
npm install dotenv-webpack --save-dev
Add this to your config file:
const Dotenv = require('dotenv-webpack');
module.exports = {
configureWebpack: {
plugins: [
new Dotenv()
]
}
}
In your .env
file make sure you add VUE_APP_
before your variables like this:
VUE_APP_VAR1=example
VUE_APP_VAR2=value
Now you can access these variables in your Vue application:
console.log(process.env.VUE_APP_VAR1); // "example"
console.log(process.env.VUE_APP_VAR2); // "value"
Here some links for reference:
- https://www.npmjs.com/package/dotenv-webpack
- https://cli.vuejs.org/guide/webpack.html
- https://cli.vuejs.org/guide/mode-and-env.html#environment-variables