Created
March 18, 2025 21:32
-
-
Save wladston/aded8390cfcd32e9ff02225cab93f25b to your computer and use it in GitHub Desktop.
Bash script to embed local fonts in CSS as Base64, making stylesheets self-contained.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# This script reads a CSS file containing links to local font files, | |
# converts them to Base64-encoded data, and replaces the `url(...)` | |
# references in the CSS. The modified CSS is output to stdout. | |
# | |
# Usage: | |
# ./embed_css_fonts.sh <CSS_PATH_PREFIX> <LOCAL_FS_PREFIX> <CSS_INPUT_FILE> | |
# | |
# Arguments: | |
# CSS_PATH_PREFIX - The prefix to strip from CSS `url(...)` paths. | |
# LOCAL_FS_PREFIX - The local filesystem path to the fonts directory. | |
# CSS_INPUT_FILE - The path to the input CSS file. | |
# | |
# Example: | |
# ./embed_css_fonts.sh "/wp-content/themes/energy/" \ | |
# "./energy/fonts/" fonts.css > fonts-embedded.css | |
# | |
# Before: | |
# @font-face { | |
# font-family: 'MyFont'; | |
# src: url('/wp-content/themes/energy/fonts/MyFont.woff2') | |
# format('woff2'); | |
# } | |
# | |
# After: | |
# @font-face { | |
# font-family: 'MyFont'; | |
# src: url(data:application/x-font-woff2;charset=utf-8;base64,AAAA...) | |
# format('woff2'); | |
# } | |
# | |
# Notes: | |
# - Works with `.woff2` fonts. | |
# - Warns of missing font files. | |
set -e | |
# Ensure correct number of arguments | |
if [[ $# -ne 3 ]]; then | |
echo "Usage: $0 <CSS_PATH_PREFIX> <LOCAL_FS_PREFIX> <CSS_INPUT_FILE>" >&2 | |
exit 1 | |
fi | |
CSS_PATH_PREFIX="$1" | |
LOCAL_FS_PREFIX="$2" | |
CSS_INPUT_FILE="$3" | |
CSS_INPUT=$(cat "$CSS_INPUT_FILE") | |
# Extract font paths from the CSS. | |
FONTS=$(echo "$CSS_INPUT" | sed -n "s/.*url('\([^']*woff2\)').*/\1/p") | |
while read -r font_path; do | |
# Remove the specified CSS path prefix. | |
CLEAN_PATH="${font_path#$CSS_PATH_PREFIX}" | |
FONT_DIR=$(dirname "$CLEAN_PATH") | |
FONT_FILE=$(basename "$CLEAN_PATH") | |
FONT_PATH="$LOCAL_FS_PREFIX/$FONT_DIR/$FONT_FILE" | |
if [[ ! -f "$FONT_PATH" ]]; then | |
echo "Warning: Font file not found: $FONT_PATH" >&2 | |
continue | |
fi | |
B64=$(base64 -i "$FONT_PATH" | tr -d '\n') | |
CSS="url(data:application/x-font-woff2;charset=utf-8;base64,$B64)" | |
# Replace only the `url(...)` part in the CSS. | |
CSS_INPUT=$(echo "$CSS_INPUT" | sed "s|url(\([^)]*$FONT_FILE'\))|$CSS|") | |
done <<< "$FONTS" | |
echo "$CSS_INPUT" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment