Managing dependencies in Node.js is achieved by using package managers like npm (Node Package Manager) and yarn.
Here’s how you can manage dependencies using npm:
1. Initialize your project: Start your project by creating a `package.json` file. This file keeps track of all packages that your project depends on. You can create this file manually or initialize it using `npm init`.
1. Install packages: You can install packages using the npm install command.
- Install dependencies: `npm install
- Install developer dependencies: `npm install
(Developer dependencies are the dependencies which are used in development but not on production)
1. Uninstall packages: You can uninstall packages using the npm uninstall command.
- `npm uninstall
1. Update packages: You can update packages using the npm update command.
- `npm update
1. View installed packages: You can view installed packages using the npm list command.
- `npm list`
1. Versioning: npm uses a semantic versioning system (semver). This means that versions have three parts: major, minor, and patch. If you want to get updates automatically when they are made, but don’t want any breaking changes, you can use tilde (~) before the version in your `package.json` file. If you use a caret (^), it means you also accept minor updates in addition to patches. If you don’t include any symbol, npm will use that version only.
An alternative to npm is yarn, which also makes use of the `package.json` file and can install packages from the npm registry. The commands are similar but can differ slightly in their syntax.
1. Audit:
- It’s also a good practice to keep an eye on your dependencies’ vulnerabilities using the npm audit command that shows your dependencies vulnerabilities and gives a suggestion to fix those.
1. Using npm ci:
- For the continuous integration workflows, it is advisable to use npm ci command. This command helps by providing excellent reproducibility across installs and is designed to be used in automated environments such as test platforms, continuous integration, and deployment.
Remember to include `package-lock.json` or `yarn-lock.json` file in your version control system. This file keeps track of the exact package versions installed, ensuring consistency across all development and production environments.