Decoupling React by environment variables

Environment variables is of the best ways to differentiate/decouple between react and it’s server side dependency.

In order to do so let’s take webpack as an example and download dotenv for webpack with npm or yarn:

yarn add --dev dotenv webpack-dotenv 


or 


npm install dotenv webpack-dotenv --save

Add the following code into the configuration files that you have for your webpack:

const Dotenv = require('dotenv-webpack')

const config = {

    devServer: { 
    plugins: [
        new Dotenv()
    ],
    node: {
        module: "empty",
        fs: "empty"
    }
}

Create a .env file in root library of the project and add the following code:

NODE_ENV=development

PROD_RESTURL= http://localhost:9000/rest
JSONSERVER_RESTURL=http://localhost:4000/rest