Skip to content

Instantly share code, notes, and snippets.

@heaven
Last active March 27, 2025 17:56
Show Gist options
  • Save heaven/d2bcc11e922d62a0db5bdb4b2a305d0c to your computer and use it in GitHub Desktop.
Save heaven/d2bcc11e922d62a0db5bdb4b2a305d0c to your computer and use it in GitHub Desktop.
Tailwind ERB preprocessor and watching tool
#!/usr/bin/env sh
INPUT_FILE=""
OUTPUT_FILE=""
WATCH=false
TAILWIND=false
TAILWIND_FLAGS=""
LAST_MODIFIED=0
print_help() {
echo "Usage: $0 -i <input_file> -o <output_file> [--watch] [--tailwind] [<tailwind_flags>]"
}
# Parse arguments
while [ "$#" -gt 0 ]; do
case "$1" in
-h|--help)
print_help
exit 0
;;
-i|--input)
INPUT_FILE="$2"
shift 2
;;
-o|--output)
OUTPUT_FILE="$2"
shift 2
;;
--watch)
WATCH=true
shift
;;
--tailwind)
TAILWIND=true
shift
;;
*)
# Collect all other arguments for Tailwind CLI
TAILWIND_FLAGS="$TAILWIND_FLAGS $1"
shift
;;
esac
done
if [ -z "$INPUT_FILE" ] || [ -z "$OUTPUT_FILE" ]; then
print_help
exit 1
fi
if [ -n "$TAILWIND_FLAGS" ] && [ "$TAILWIND" != "true" ]; then
echo "Warning: Use --tailwind to enable Tailwind CLI preprocessing."
fi
get_modified_time() {
if command -v stat >/dev/null 2>&1; then
if stat --version >/dev/null 2>&1; then
stat -c %Y "$INPUT_FILE" 2>/dev/null
else
stat -f %m "$INPUT_FILE" 2>/dev/null
fi
else
echo "0"
fi
}
render_file() {
CURRENT_MODIFIED=$(get_modified_time)
if [ "$CURRENT_MODIFIED" -gt "$LAST_MODIFIED" ]; then
echo "Rendering $INPUT_FILE..."
if [ "$TAILWIND" = "true" ]; then
# Memoize the original directory
ORIGINAL_DIR=$(pwd)
# Get absolute path of input file
cd "$(dirname "$INPUT_FILE")" || exit 1
ABS_INPUT_DIR=$(pwd)
ABS_INPUT_FILE="$ABS_INPUT_DIR/$(basename "$INPUT_FILE")"
# Ensure we operate from the original directory
cd "$ORIGINAL_DIR" || exit 1
cd "$(dirname "$OUTPUT_FILE")" || exit 1
# Get absolute path of output file
ABS_OUTPUT_DIR=$(pwd)
ABS_OUTPUT_FILE="$ABS_OUTPUT_DIR/$(basename "$OUTPUT_FILE")"
# Change to the input file's directory (if different)
if [ "$ABS_INPUT_DIR" != "$ORIGINAL_DIR" ]; then
cd "$ABS_INPUT_DIR" || exit 1
fi
# Run ERB and Tailwind processing
erb "$ABS_INPUT_FILE" | npx @tailwindcss/cli -i - -o "$ABS_OUTPUT_FILE" $TAILWIND_FLAGS
# Switch back to the original directory
cd "$ORIGINAL_DIR" || exit 1
else
erb "$INPUT_FILE" > "$OUTPUT_FILE"
fi
LAST_MODIFIED="$CURRENT_MODIFIED"
fi
}
if [ "$WATCH" = "true" ]; then
echo "Watching $INPUT_FILE for changes..."
while true; do
render_file
sleep 1
done
else
render_file
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment