Ad

Env-cmd Environment Variables In React

- 1 answer

I seem to have tried every which way variation of the env-cmd command but cannot work out why I can't access the variables

I originally followed this tutorial https://www.youtube.com/watch?v=3SH5AQsHypA

but the docs have since changed and so you need to use the command -e unlike the video so my package.json command reads...

"dev-server": "env-cmd -e dev webpack-dev-server",

any my .env-cmdrc reads...

{
    "dev" : {
        "BASE_URL" : "development"
    },
    "qa" : {
        "BASE_URL" : "qa"
    },
    "prod" : {
        "BASE_URL" : "prod"
    }
}

But I just cannot access process.env.BASE_URL for some reason. Any help is greatly appreciated

Ad

Answer

For anyone interested this far along. This was actually solved in the end by using the Dotenv-webpack library

https://www.npmjs.com/package/dotenv-webpack

in your webpack config file;

const Dotenv = require('dotenv-webpack');

pass the parameter of env to module.exports

module.exports = (env) => {
 let ENV_CONFIG;

 if(env === 'dev'){
     ENV_CONFIG = new Dotenv({path: './environment/.env-dev'})
 }

 if(env === 'staging'){
     ENV_CONFIG = new Dotenv({path: './environment/.env-staging'})
 }

 if(env === 'production'){
     ENV_CONFIG = new Dotenv({path: './environment/.env-production'})
 }
}

then in plugins...

plugins : [
    ENV_CONFIG
]

your package.json script may then look something like..

"build:prod": "webpack -p --env production"

You should then be able to access your variables under process.env like so;

process.env.SERVER_URL
Ad
source: stackoverflow.com
Ad