Example Codes:
Here's a table summarizing the key differences:
Command | What it does |
---|---|
npm install <package-name> | Installs a new package and its dependencies. |
npm update | Updates existing packages to their latest compatible versions. |
Bonus points:
- By default,
npm install
considers both regular dependencies and development dependencies listed in your project'spackage.json
file.npm update
ignores development dependencies unless you use the--dev
flag. - Sometimes, updates might introduce changes that break your code. It's good practice to test your project after running
npm update
.
Example Codes:
Let's say you want to add a package called "axios" (used for making HTTP requests) to your project. Here's the command:
npm install axios
This will download and install the axios
package and its dependencies into your project's node_modules
folder.
Updating existing packages:
Now, imagine you want to update all the currently installed packages to their latest compatible versions. You can use:
npm update
This will check for updates for all the packages in your node_modules
folder and install any compatible newer versions.
Updating a specific package:
If you only want to update a specific package (like axios
), you can use:
npm update axios
This will update only the axios
package to its latest compatible version.
Updating development dependencies:
Remember, by default npm update
skips development dependencies. To update them as well, use the --dev
flag:
npm update --dev
- yarn: Another popular package manager offering similar functionality to
npm
but with some performance improvements and a focus on security. You can install it globally and then use commands likeyarn add <package-name>
for installation andyarn upgrade
for updates.
Git-based package installation:
Some packages might be hosted on platforms like GitHub and offer installation directly from the repository. You can specify the Git URL in your package.json
file with a special syntax (e.g., git+ssh://[email protected]/username/package.git
). This approach gives you more control over the specific version being installed.
Manual Download and Installation:
For very specific scenarios, you might download a package as a zip file or archive and manually place it within your project structure. However, this method is generally discouraged as it makes dependency management more cumbersome.
Choosing the right approach depends on your specific needs and preferences. Here's a quick guideline:
- For most cases,
npm
is the recommended and widely used option. - If you prioritize speed and security, consider exploring
yarn
. - Git-based installation might be useful for private packages or specific version control needs.
- Manual installation is generally not recommended for production use.
node.js npm