Reputation: 28138
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
?
Upvotes: 11
Views: 14471
Reputation: 1012
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
Upvotes: 10