Skip to content

Instantly share code, notes, and snippets.

@MatthewAlner
Created May 12, 2024 10:55
Show Gist options
  • Select an option

  • Save MatthewAlner/6fe90e32eb32d111e7b95a4e52666043 to your computer and use it in GitHub Desktop.

Select an option

Save MatthewAlner/6fe90e32eb32d111e7b95a4e52666043 to your computer and use it in GitHub Desktop.
Bash functions to automatically detect and use the correct JavaScript package manager for installing dependencies and running scripts defined in package.json. Supports Yarn, npm, pnpm, and Bun.
# Function to install JavaScript dependencies based on the lock file present in the current directory.
# as this uses else if statements, it will only install dependencies for the first lock file found
# this means you can use the order as a preference list
install_js_dependencies() {
if [ -f "yarn.lock" ]; then
echo "Using Yarn"
yarn install
elif [ -f "package-lock.json" ]; then
echo "Using npm"
npm install
elif [ -f "pnpm-lock.yaml" ]; then
echo "Using pnpm"
pnpm install
elif [ -f "bun.lockb" ]; then
echo "Using bun"
bun install
else
echo "No lock file found. Please ensure you are in the right directory and the lock file exists."
return 1
fi
}
# Function to run a JavaScript script using the appropriate package manager based on the lock file present in the current directory.
# Parameters:
# - script_name: The name of the script to run.
# Returns:
# - 0 if the script is successfully executed.
# - 1 if there is an error or if no lock file is found.
run_js_script() {
local script_name=$1
if [ -z "$script_name" ]; then
echo "Please provide a script name as the first parameter."
return 1
fi
if [ -f "yarn.lock" ]; then
echo "Using Yarn"
yarn run "$script_name"
elif [ -f "package-lock.json" ]; then
echo "Using npm"
npm run "$script_name"
elif [ -f "pnpm-lock.yaml" ]; then
echo "Using pnpm"
pnpm run "$script_name"
elif [ -f "bun.lockb" ]; then
echo "Using bun"
bun run "$script_name"
else
echo "No lock file found. Please ensure you are in the right directory and the lock file exists."
return 1
fi
}
alias yy='install_js_dependencies && run_js_script start'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment