[Learn Open Source] Learn install-pkg in 5 minutes
Let me help you reduce the pain while reading the open-source project. I will focus on relative small project which means easy to read.
What is install-pkg and why did I choose this one to read with?
What is install-pkg
Install package programmatically. Detect package managers automatically. This is the introduction in the project introduction. Now let’s dig into how Antony Fu achieved it by using less than 100 lines of code. It is easy to read and understand.
How to read source code(optional)
Once you choose an open-source project. First, you need to decide if you want to run it locally.
For running an open-source project locally you better check the contribution guide which includes step-by-step instructions to help you set up the project locally.
I have a good example in the previous article which include more detail you can check it.
[Source Code]Vue3 — Utility Function In 5 Minutes
impress interviewee by reading source code
If you just want to quickly view the source code online I recommend you just use the vscode online editor mode which is supported by Github already. You just need to change .com to be .dev
For example https://github.dev/antfu/install-pkg
Dive into Install-pkg source code
Firstly let’s look at the project structure. The only files worth reading are the package.json and files inside src folder.
Let’s look at the src folder. Index.ts is the entry point. It exports the detect and installs.
Let’s look at detect.ts file:
As you can see the LOCK dictionary uses a lock file as key and pnpm, yarn or npm as the value.
process.cwd() returns the current working directory.
findUp is a small library that finds a match from left (keys) with options in the current working directory.
In line 14： the agent is the return value from the LOCKS dictionary. The return value is from one of the matched results: pnpm, yarn or npm.
Let’s look at install.ts file:
It checks if it is string if not convert it to string. This code is worth noting.
names = [names]
This is the last step for this code. If you have any questions about the above code you can check execa documentation
Firstly, we know two libraries might be useful in our future development.
Secondly, the code is clean and easy to understand. detect.ts and install.ts basically explain the purpose by the file name itself no need to guess.
The only improvement I can see is the edge case handling. There are chances that the package manager is not recognizable.
Don’t be afraid of writing your utils repository and share it with the public. It doesn’t necessarily be a complex one like Vue or react. You can write a small tool. The best way to learn is to get your hands dirty. Thanks for reading this article hope you like it.
GitHub - antfu/install-pkg: Install package programmatically.
You can't perform that action at this time. You signed in with another tab or window. You signed out in another tab or…