Home > Blockchain >  react exclude config files from build
react exclude config files from build

Time:02-11

In my react app I have 4 separate config files for 4 different environments to run in, test for unit tests, dev use while developing, staging for the staging environment (almost identical to prod) and prod for the actual customer facing production server.
One setting of those config files is the api address (127.0.0.1:7777 for dev, api.staging-app.com for staging, api.app.com for prod.

React will use the config file corresponding to the REACT_APP_NODE_ENV variable. But I have recently noticed that react will always bundle ever config file to be discovered by nosy users.

Since I would like to keep the location of the staging server secret (its still protected, even if it were discovered), I would like to exclude all the unused config files from the webpack build. Is there a way to do this?

CodePudding user response:

I don't know why this works but I did it like this:

if(process.env.REACT_APP_NODE_ENV==="prod"){
    var config=require("../config_prod.json")
}
if(process.env.REACT_APP_NODE_ENV==="dev"){
    var config=require("../config_dev.json")
}
if(process.env.REACT_APP_NODE_ENV==="test"){
    var config=require("../config_test.json")
}
else if(process.env.REACT_APP_NODE_ENV==="staging"){
    var config=require("../config_staging.json")
}




export default config;

this way any unused config file won't end up in the production bundle. This only works if process.env is in the if clause, if it is for example Math.random()<0.5, it will bundle everything

  • Related