Recently I have started to refactor one of our application which is bootstrapped using create-react-app. One of the major tasks is to rewrite the way that configuring the env variables. create-react-app does provide a series of ways to set the variables for both development and production usage. But, to be honest, it’s not enough for the fact of our team since we own multiple servers(we call it stacks) including dev, qa, stage, and then the prod for real customer usage. That means it’s a must feature to distinguish these stacks. create-react-app can not work in that way then we asked the devops team to inject the env variables before build the app for the specify stacks. It worked well, but, we still want to own the control by ourselves. Since:
- Those env variables are absolute public and will not be changed frequently.
- The build script(owed by DevOps) for each app are almost the same except the env variables, if they are being removed from the script and configured by the app self, the DevOps only need to maintain one copy of the script.
what I will do will be very simple, maybe a little bit rude, but, it really works. Following are the detailed steps:
1. prepare conf for each stack.
2. Install dotenv and ini as dev-dependencies
3. create a js file: env.js.
So my idea is,
- read the env variable stack(e.g. process.env.stack) and find the file named .env.${stack}
- Load the content from the file and re-generate .env(ini sytax) in the root.
Next and the last step is to executing env.js before start/build/test the application.Then rescripts(the build cmd of create-react-app) will read the .env file to get the correct env variables.
Tips
If you are going to have a try, please be noticed that the file path and stack name are hardcoded for my application, it’s required to go through the env.js and make some changes.
About me
My name is Wang Pin. I’m a beginner in English and writing articles. I worked for a medium team of HP(from 2016 till now) as an engineer. This is my first story in Medium.