npm (Node Package Manager) is a package manager and distribution tool for Node.js, used to manage dependencies in projects.
Basic Differences
npm install <package_name>: This command installs the specified package into thenode_modulesdirectory without modifying thepackage.jsonfile. If the dependency is already listed inpackage.jsonwith a specified version, it will be installed using that version; otherwise, the latest version is installed.npm install <package_name> --save: This command not only installs the package but also adds it as a dependency to thepackage.jsonfile. Consequently, when others clone your project and runnpm install, this package will be installed automatically.
Usage Scenarios and Importance
- Development Dependencies vs. Production Dependencies: In practical development, libraries required for the application to run are typically listed as production dependencies, while tools for testing and building projects are designated as development dependencies. Using the
--saveflag adds dependencies to thedependenciessection, which is the default behavior. To add a dependency as a development dependency, use--save-dev. - Project Maintainability and Collaboration: Explicitly recording dependencies in
package.jsonensures that team members or deployers can consistently install identical dependency versions, thereby avoiding issues caused by version discrepancies.
Example
Suppose you are developing a Node.js web application and need to install the Express framework. You would run:
bashnpm install express --save
This adds Express to the dependencies section of your package.json, ensuring that other developers can install the same package when they clone your project using npm install.
Summary
In short, the key difference between npm install <package_name> and npm install <package_name> --save is that the latter modifies the package.json file to include the installed package in the project dependencies, which is critical for dependency management. Starting from npm 5.x, --save became the default behavior, so with newer npm versions, even running npm install <package_name> alone will add dependencies to package.json.