Last active
January 16, 2025 10:42
-
-
Save aculich/12f21c60dce10e1814eac5bfe791be61 to your computer and use it in GitHub Desktop.
converts a given JavaScript file into a bookmarklet using terser
This file contains 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
#!/usr/bin/env bash | |
# Overview: | |
# This script ensures that npm and the terser package are installed, | |
# and it converts a given JavaScript file into a bookmarklet. The | |
# output is saved as bmlet_<original_file_name>.js. The script does the following: | |
# 1. Checks if npm is installed. | |
# 2. Installs terser globally if not already installed. | |
# 3. Minifies the provided JavaScript file and converts it into a bookmarklet format. | |
# 4. Outputs the result into a new file named bmlet_<input_file_name>.js. | |
# | |
# Usage: | |
# ./bookmarkletify.sh <input_file.js> | |
# | |
# Example: | |
# ./bookmarkletify.sh example.js | |
# This creates bmlet_example.js with the bookmarkletified JavaScript. | |
# Check if npm and terser are installed | |
if ! command -v npm &> /dev/null; then | |
echo "Error: npm is not installed. Please install Node.js and npm first." | |
exit 1 | |
fi | |
if ! command -v terser &> /dev/null; then | |
echo "Installing terser..." | |
npm install -g terser | |
fi | |
# Check if a file name is provided | |
if [ -z "$1" ]; then | |
echo "Usage: $0 <file.js>" | |
exit 1 | |
fi | |
INPUT_FILE="$1" | |
BASENAME=$(basename -- "$INPUT_FILE") | |
OUTPUT_FILE="bmlet_${BASENAME%.js}.js" | |
# Minify and wrap the JavaScript in a bookmarklet format | |
terser "$INPUT_FILE" --compress --mangle | sed 's/^/javascript:(function(){/' | sed 's/$/})();/' > "$OUTPUT_FILE" | |
if [ $? -eq 0 ]; then | |
echo "Bookmarkletified version saved as: $OUTPUT_FILE" | |
if [[ "$OSTYPE" == "darwin"* ]]; then | |
cat "$OUTPUT_FILE" | pbcopy | |
echo "And copied to the pasteboard" | |
fi | |
else | |
echo "Error occurred while generating the bookmarklet." | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment