BASH

Automate Frontend Build and Sync

Streamline your web development workflow by automating the 'npm install' and 'npm run build' steps for frontend projects, then synchronizing the build output to a target directory.

#!/bin/bash

# Path to your frontend project directory (where package.json is)
FRONTEND_PROJECT_DIR="/home/user/my-frontend-app"

# Target directory for the build output (e.g., web server root or backend public folder)
TARGET_BUILD_DIR="/var/www/html/public"

# Name of the build output directory relative to FRONTEND_PROJECT_DIR (e.g., 'dist', 'build')
BUILD_OUTPUT_SUBDIR="dist"

# --- Script Start ---

# Check if project directory exists
if [ ! -d "$FRONTEND_PROJECT_DIR" ]; then
  echo "Error: Frontend project directory '$FRONTEND_PROJECT_DIR' does not exist." >&2
  exit 1
fi

# Change to the project directory
cd "$FRONTEND_PROJECT_DIR" || { echo "Failed to change directory to '$FRONTEND_PROJECT_DIR'."; exit 1; }

echo "Running npm install..."
npm install || { echo "npm install failed. Exiting."; exit 1; }

echo "Running npm run build..."
npm run build || { echo "npm run build failed. Exiting."; exit 1; }

BUILD_SOURCE_PATH="$FRONTEND_PROJECT_DIR/$BUILD_OUTPUT_SUBDIR"

# Check if build output directory exists after build
if [ ! -d "$BUILD_SOURCE_PATH" ]; then
  echo "Error: Build output directory '$BUILD_SOURCE_PATH' not found. Check your build script and 'BUILD_OUTPUT_SUBDIR' variable." >&2
  exit 1
fi

echo "Synchronizing build output from '$BUILD_SOURCE_PATH/' to '$TARGET_BUILD_DIR/'..."
# Use rsync to copy files, deleting files in TARGET_BUILD_DIR that are not in BUILD_SOURCE_PATH
# -a: archive mode (preserves permissions, timestamps, etc.)
# -v: verbose output
# -z: compress file data during the transfer
# --delete: delete extraneous files from dest dir (not in source)
rsync -avz --delete "$BUILD_SOURCE_PATH/" "$TARGET_BUILD_DIR/" || { echo "rsync failed. Exiting."; exit 1; }

echo "Frontend build and sync complete."
How it works: This script automates the typical frontend build process for web developers. It navigates to a specified `FRONTEND_PROJECT_DIR`, executes `npm install` to update dependencies, and then runs `npm run build` to compile frontend assets. After a successful build, it uses `rsync -avz --delete` to efficiently synchronize the contents of the build output directory (e.g., `dist`) to a `TARGET_BUILD_DIR`. The `--delete` flag ensures that any files in the target that are no longer present in the source are removed, keeping the target clean.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs