Node Managing Dep

Managing Node.js Dependencies

In the Node.js ecosystem, third-party packages that your project relies on are called dependencies. Managing these correctly is a vital skill for preventing bugs and keeping your project secure.

In this tutorial, you will learn the difference between standard and development dependencies, how to uninstall packages, and how NPM versions your packages.


1. Regular Dependencies vs. devDependencies

When you install a package, you need to decide if the package is required for the application to run in production, or if it is only needed while you are coding.

Standard Dependencies

These are packages your app needs to function. Examples include web frameworks (express), database drivers (mongoose), or utility libraries (lodash).

Install them using the standard command:

npm install express

devDependencies

These are tools you use while developing, but your live application does not need them. Examples include testing frameworks (jest), auto-restarters (nodemon), or code formatters (prettier).

To install a package as a devDependency, add the --save-dev flag (or -D for short):

npm install nodemon --save-dev

Your package.json will now split them into two distinct categories:

package.json

{
  "dependencies": {
    "express": "^4.18.2"
  },
  "devDependencies": {
    "nodemon": "^3.0.1"
  }
}

2. Removing Dependencies

If you realize you no longer need a package, you shouldn't just delete it from your code. You must properly uninstall it so NPM can remove it from node_modules and update your package.json.

To uninstall a package, use npm uninstall <package-name>:

npm uninstall express

3. Understanding Semantic Versioning (SemVer)

If you look closely at your package.json dependencies, you will see version numbers like "^4.18.2". NPM uses a system called Semantic Versioning consisting of three numbers: Major.Minor.Patch.

The Caret (^) and Tilde (~) Symbols

NPM prefixes versions with symbols to dictate how safely updates can be applied when you run npm install:


4. Keeping Dependencies Updated

Over time, package authors release bug fixes and new features. You can check if any of your dependencies have newer versions available by running:

npm outdated

If updates are available, you can safely apply minor and patch updates according to your SemVer rules by running:

npm update

Exercise

?

Which flag should you use to install a testing framework that is ONLY needed during development?