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
Published 4 years ago
Updated 3 years ago

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.

egghead
egghead
~ 35 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today