đź§± How to Change the Build Path in a React Application
Sometimes you may want your React app’s build output to be moved to a different directory — for example, into a server’s public folder. In this guide, we’ll see how to do that using a simple shell script that runs automatically after the build process.
🪶 Step 1: Create a Shell Script
Create a new shell script file named {file-name}.sh inside the root directory of your React project.
🪶 Step 2: Update package.json
Open your package.json file and add a new script named postbuild right below the existing build script:
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"postbuild": "./{file-name}.sh"
}
đź’ˇ Note:
If you’re on Windows, make sure you have Git Bash or WSL installed to run the script, since native Command Prompt doesn’t support bash syntax.
You can run it manually using:
bash {file-name}.sh
🪶 Step 3: Write the Shell Script
The shell script will move your built files to a new directory after every build.
Here’s a sample script you can modify as needed:
#!/bin/bash
# Define your app name or set it as an environment variable
APP_NAME="my-react-app"
# If the target folder exists, remove its contents first, then move the new files
if [ -d "./../server/public/${APP_NAME}/" ]; then
echo "Target folder exists. Cleaning it..."
rm -rv ./../server/public/${APP_NAME}/*
# Move the build files (use cp -r instead of mv if you want to keep a copy)
mv -v build/* ./../server/public/${APP_NAME}/
else
# Otherwise, create the target folder and then move the files
echo "Creating target folder and moving files..."
mkdir -p ./../server/public/${APP_NAME}
mv -v build/* ./../server/public/${APP_NAME}/
fi
đź§© Tip:
mvmoves the files (thebuildfolder will be emptied afterward).- Use
cp -rinstead if you prefer to copy the files and keep the originalbuildintact.
đź§© How It Works
When you run:
npm run build
React completes its build process and then automatically executes the postbuild script.
This script checks if the target directory already exists:
- ✅ If it exists — the folder is cleared, and new build files are moved in.
- 🆕 If not — it creates the folder and moves the files.
⚠️ Make sure your project structure matches this example:
/my-project ├── react-app/ └── server/Adjust the relative path (
./../server/public/) if your setup differs.
đź§ Customize It
You can tweak this script for your own directory structure or workflow.
To explore more possibilities, check out a few beginner-friendly shell scripting tutorials — you’ll be surprised how much you can automate.
🎉 Final Thoughts
That’s it! With this small setup, your React app’s build files will automatically be relocated right after each build — no manual steps needed.
Happy Coding! 🥳

Top comments (1)
Thank you :)