DEV Community

Molly Graham
Molly Graham

Posted on

A Beginner’s Digest of Lessons Learned in React - Part I

About Me

As a perfectionist and beginner programmer who suffers from imposter syndrome, I must admit I am a bit intimidated to be writing about what I am learning at my current job as an associate software engineer; however, in the spirit of learning in public, I hope to not only share my experiences and advice but also push past my discomfort and hopefully learn even more.

I started as a front end developer on a React project about one month ago, and seeing as this is the first Scrum team I’ve been a part of, I have already learned a lot. From working with new libraries to learning the ins-and-outs of agile development, I hope to capture the little lessons or tips I’ve learned here on a recurring basis.

Dynamic Environment Variables

For this week, I’d like to share a few tips about writing custom npm scripts.

In the app I am currently working on, we needed to set two different custom environment variables in our React start scripts, because our app interacts with two separate API endpoints. There are two different types of users for our app, and each user interacts with a different UI. Our thought for developing in these different environments was to tell the app which API to hit based on an environment variable set in npm scripts.

I had previously only defined environment variables in a .env file, and so this was the first time I had dynamically set an environment variable in a script. I was a little unsure of the exact syntax of the script at first, but after trial and error, the scripts were working and spinning up the correct environments!

"scripts": {
"start": "react-scripts start",
"start-user1": "cross-env REACT_APP_API_URL=https://iamuser1.com REACT_APP_ENV_CONFIG=user 1 npm start",
"start-user2": "cross-env REACT_APP_API_URL=https://iamuser2.com REACT_APP_ENV_CONFIG=user 2 npm start"
}

A Few Tips

Here are a few points I learned along the way that might be helpful to you as you write your own custom scripts.

  1. By default, we have access to the NODE_ENV variable, but we create our own custom variables with the prefix REACT_APP.

  2. Consider using a small package called cross_env (published by by Kent C. Dodds) in order to enable functionality across multiple platforms.

  3. Using “&&” in a script will allow two commands to execute consecutively; therefore, the second command will only run if the first one is successful.

  4. In order to execute a custom script, we must include the word “run” before the command (i.e. “npm run start-my-custom-script”)

Hopefully you find this helpful, and I look forward to posting more about what I’m learning as a FE engineer!

Top comments (0)