I am using Vue and webpack, with an environment variable that tells webpack to build for production or development.
This is working:
NODE_ENV=production webpack
console.log(process.env)
But, this documentation explains that you can use different .env
files according to production or development mode, to change variables in your app.
.env file
VUE_APP_ROOT=http://localhost:8000/
VUE_APP_BASE_URL=http://localhost:8000/api/
.env.prod file
VUE_APP_ROOT=http://realaddress/
VUE_APP_BASE_URL=http://realaddress/api/
But I'm not clear on how these .env files get accessed? Apparently this works when you use vue-cli
, but in my app this logs undefined:
console.log("environment variables")
console.log(process.env.VUE_APP_ROOT)
console.log(process.env.VUE_APP_BASE_URL)
How can I access different .env
files depending on production mode, without vue-cli
?
One solution is to have multiple . env files which each represent different environments. In practice this means you create a file for each of your environments: .
Using environment variables is a somewhat common practice during Development but it is actually not a healthy practice to use with Production. While there are several reasons for this, one of the main reasons is that using environment variables can cause unexpected persistence of variable values.
you can use the dotenv plugin.
// webpack.config.js
const Dotenv = require('dotenv-webpack');
module.exports = {
...
plugins: [
new Dotenv()
]
...
};
To load file based on environment, you can leverage process.env.NODE_ENV
:
// webpack.config.js
const Dotenv = require('dotenv-webpack');
const env = process.env.NODE_ENV;
module.exports = {
...
plugins: [
new Dotenv({
path: `./.env.${env === "production" ? "prd" : "dev"}`,
})
]
...
};
You can see vue-cli doing a similar thing in this repo
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