Adding and Removing Packages
When you find a cool tool on the NPM website, you need to "install" it to use it in your code.
There are two main ways to install packages, depending on when you need them.
1. Production Dependencies (--save)
These are the "Main Ingredients." Your website needs these to function for the user. If you are building a calculator, the math library you use is a production dependency.
The Command:
npm install lodash
- What happens? NPM downloads the code into
node_modulesand adds it to the"dependencies"section of yourpackage.json. - Shortcut: You can just type
npm i lodash.
2. Dev Dependencies (--save-dev)
These are the "Kitchen Tools." You need a knife and a pan to cook the meal, but the customer doesn't eat the knife!
"DevDeps" are tools you only use while you are coding (like a tool that auto-refreshes your browser or a code-cleaner).
The Command:
npm install nodemon --save-dev
- Shortcut: You can use
-Das a shortcut:npm i nodemon -D. - Look inside: These will appear in a special
"devDependencies"section in yourpackage.json.
What is this package-lock.json file?
The moment you install your first package, a new, scary-looking file called package-lock.json will appear.
Don't delete it! Think of it as a Security Seal. While package.json says "I need a math library," the package-lock.json says "I need exactly version 4.17.21 of the math library with this specific security ID."
It ensures that if 10 people are working on the same project at CodeHarborHub, everyone has the exact same version of the code.
Removing a Package
If you decide you don't like a tool, don't just delete the folder manually. Use the "clean-up" command:
npm uninstall lodash
This safely removes the code from node_modules and deletes the line from your package.json recipe.
Summary Comparison
| Type | Command | Where it goes | Purpose |
|---|---|---|---|
| Dependency | npm i <name> | "dependencies" | Needed for the website to run. |
| DevDependency | npm i <name> -D | "devDependencies" | Only needed by the developer. |
Summary Checklist
- I can install a package using
npm i. - I understand that
-Dis for tools only I (the developer) use. - I know that
package-lock.jsonis a security lock for versions. - I can use
npm uninstallto keep my project clean.