2月17日 23:29
What is npm and how does it work as a package manager for JavaScript projects?
npm (Node Package Manager) is the default package manager for Node.js, used to install, manage, and publish JavaScript packages.
Core Features
npm provides the following main functionalities:
- Package Management: Download and install third-party packages from npm registry
- Dependency Management: Automatically handle dependencies between packages
- Version Control: Manage package versions using semantic versioning
- Script Execution: Define and run project scripts through package.json
- Package Publishing: Publish custom packages to npm registry for others to use
How It Works
npm workflow:
- Initialize Project: Run
npm initto create package.json file - Install Dependencies: Run
npm installto install dependencies defined in package.json - Dependency Resolution: npm resolves the dependency tree to determine all packages and versions to install
- Download and Install: Download packages from npm registry to node_modules directory
- Lock Versions: Generate package-lock.json to record exact dependency versions
package.json Structure
json{ "name": "my-project", "version": "1.0.0", "description": "Project description", "main": "index.js", "scripts": { "start": "node index.js", "test": "jest" }, "dependencies": { "express": "^4.18.0" }, "devDependencies": { "jest": "^29.0.0" } }
Common Commands
npm install <package>: Install a packagenpm install -g <package>: Install package globallynpm install --save-dev <package>: Install as development dependencynpm update: Update dependency packagesnpm uninstall <package>: Uninstall a packagenpm run <script>: Run scripts defined in package.json
Dependency Types
- dependencies: Production dependencies, required for application runtime
- devDependencies: Development dependencies, only needed during development
- peerDependencies: Peer dependencies, provided by host project
- optionalDependencies: Optional dependencies, installation failure won't interrupt
npm ensures consistency and reproducibility of project dependencies through package.json and package-lock.json files, making it a core tool in the modern JavaScript development ecosystem.