A tip to auto run the package manager for your project

Pnpm is great and so is Yarn

They're great. The only problem is when I don't remember which I chose for a project.

Add this to your .zshrc or .bashrc and give the command an alias that you like.


function p {
# Get the root of the Git repo for mono-repos
local git_root
git_root=$(git rev-parse --show-toplevel 2>/dev/null)
# If the Git root is empty, then we're not in a Git repo so use the current folder
if [ -z "$git_root" ]; then
git_root="."
fi
local lock_file
if [ -e "$git_root/yarn.lock" ]; then
lock_file="yarn.lock"
elif [ -e "$git_root/pnpm-lock.yaml" ]; then
lock_file="pnpm-lock.yaml"
elif [ -e "$git_root/package-lock.json" ]; then
lock_file="package-lock.json"
else
echo "No lock file found in the Git root. Initialize the project with Yarn, pnpm, or npm."
fi
# Run the command with the lock file
if [ "$lock_file" = "yarn.lock" ]; then
# shortcut to make this more like npm i, yarn doesn't have yarn i so we'll add it in to mirror that functionality
if [ "$1" = "i" ]; then
shift
yarn install "$@"
else
yarn $*
fi
elif [ "$lock_file" = "pnpm-lock.yaml" ]; then
pnpm $*
elif [ "$lock_file" = "package-lock.json" ]; then
npm $*
else
echo "No lock file found in the Git root. Initialize the project with Yarn, pnpm, or npm. Falling back to pnpm"
pnpm $*
fi
}