Recently, I needed to optimize the build process for my website https://es.learnlanguage.online. Since I work with different environments, my package.json was cluttered with repetitive scripts for each environment – things like build-and-deploy:test, build-and-deploy:stage, and so on. As a developer, I find this kind of repetition frustrating, and I suspect you do too. I decided to consolidate these scripts into a single shell file, which helped me streamline my build process, clean up my package.json, and make the whole setup more flexible and scalable. In this article, I’ll show you how to do the same.
Here’s an example of the repetitive scripts I had in my package.json – I’m willing to bet you’ve seen something similar:
"build-and-deploy:test": "NEXT_PUBLIC_TARGET_ENV=test next build && npm run set-sourcemaps && npm run deploy:test",
"build-and-deploy:stage": "NEXT_PUBLIC_TARGET_ENV=stage next build && npm run deploy:stage",
"build-and-deploy:prod": "NEXT_PUBLIC_TARGET_ENV=prod && npm run generate-sitemap && npm run deploy:prod"
My goal was to reduce this to a single script that I could run interactively, like this:

Combining repetitive npm scripts into one shell script
First, create a build-and-deploy.sh file and add the following code:
#!/bin/bash
echo "Please select a target environment:"
options=("test" "stage" "prod")
select target in "${options[@]}"; do
case $target in
test)
NEXT_PUBLIC_TARGET_ENV=test next build && npm run set-sourcemaps && npm run deploy:test
break
;;
stage)
NEXT_PUBLIC_TARGET_ENV=stage next build && npm run deploy:stage
break
;;
prod)
NEXT_PUBLIC_TARGET_ENV=prod && npm run generate-sitemap && npm run deploy:prod
break
;;
*)
echo "Invalid option $REPLY. Please select a valid target."
;;
esac
done
Next, update your package.json by removing all those repetitive scripts and replacing them with a single one:
"build-and-deploy": "./scripts/build-and-deploy.sh"
Finally, make sure the script has execute permissions:
chmod +x scripts/build-and-deploy.sh
Now let’s test the script. When I run npm run build-and-deploy, I get exactly what I expected:

I hope you found this article helpful!
