Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read different .env files depending on production or development mode?

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 ?

like image 803
Kokodoko Avatar asked Jun 02 '18 10:06

Kokodoko


People also ask

Can you have multiple .env files?

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: .

Should you use .env in production?

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.


1 Answers

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

like image 119
loveky Avatar answered Oct 07 '22 18:10

loveky