Make a zsh function alias to enforce using yarn commands when in a yarn project

Elijah Manor
InstructorElijah Manor
Share this video with your friends

Social Share Links

Send Tweet

When you or your team work on various npm or yarn projects it gets hard to remember which one is which. This lesson shows you how to create a custom npm zsh function alias to remind yourself to use yarn commands when there is a yarn.lock file in the directory.

Elijah Manor: [0:00] Let's open up our zshrc configuration file from our user's home directory in whatever editor you want. I'll use VS Code. Now, we'll define a function alias called npm. If we find the existence of a yarn.lock file, we'll echo a custom message, "This is a yarn project. Why don't you use it !?"

[0:22] Otherwise, we'd like to call the same npm command that we attempted passing the same arguments. $1 would represent the first argument but we want all of them, so we use $@ instead.

[0:38] However, this would cause an infinite loop since we redefined npm to be the name of our function alias. Instead, we could use the command command which will ignore any shell functions so that the real npm will be invoked.

[0:55] Let's now open up the integrated terminal and we'll source our updated zshrc configuration file to make sure the new function alias is defined. Then we'll navigate to a project that I created with npm and we can double check by listing out any yarn files, and there are none. We should be able to run any npm command and it will go through just fine, which it does.

[1:21] Let's switch to a yarn project. Let's verify that indeed it has a yarn.lock file, and it does. We'll try to list available tasks with npm run. However, our new function alias stops us in our tracks and warns us to use yarn commands instead. Instead, I could execute yarn run to see available tasks. I could run them here or I could call them directly.