Search code examples
javascriptreactjscreate-react-app

How can I build the dev env and the prod env differently in build time? etc) db config


i am using create-react-app, i should set the project prod env, dev env diffrently and deploy to dev server & prod server(seperated)

in now, i cant found the good way about this issue, i am changing myself config value before deploy to server(prod or dev). but it is inefficient and unstable.

for example)

//config.json

...
"db": {
    "prodSchema": "foo_p",
    "devSchema": "foo_d",
    "username": "dany",
    "password": "****",
    "host": "123.456.789.111:3306",
    "dialect": "mysql"
},
...

and use

//config use.js

in deploy, check & change...

//db.connect(config.prodSchema)
db.connect(config.devSchema)

i want get set way before 'yarn build' prod env & dev env differently in create-react-app


Solution

  • using webpack you can apply the environment plugin and check for the environment variables to check which profile you should use.

    browserify has a transformation called envify for the very same purpose.

    then you can do something like this:

    import axios from "axios";
    
    const env = process.env.NODE_ENV || "development";
    
    const config = {
      development: {
        baseURL: "http://127.0.0.1:3000",
      },
      staging: {
        baseURL: "https://mysuperservice.herokuapp.com",
      },
      production: {
        baseURL: "https://mysuperservice.com",
      },
    };
    const api = axios.create({
      baseURL: config[env].baseURL,
      headers: {
        "x-api-key": "ABC",
      },
    });