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:

  1. Package Management: Download and install third-party packages from npm registry
  2. Dependency Management: Automatically handle dependencies between packages
  3. Version Control: Manage package versions using semantic versioning
  4. Script Execution: Define and run project scripts through package.json
  5. Package Publishing: Publish custom packages to npm registry for others to use

How It Works

npm workflow:

  1. Initialize Project: Run npm init to create package.json file
  2. Install Dependencies: Run npm install to install dependencies defined in package.json
  3. Dependency Resolution: npm resolves the dependency tree to determine all packages and versions to install
  4. Download and Install: Download packages from npm registry to node_modules directory
  5. 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 package
  • npm install -g <package>: Install package globally
  • npm install --save-dev <package>: Install as development dependency
  • npm update: Update dependency packages
  • npm uninstall <package>: Uninstall a package
  • npm run <script>: Run scripts defined in package.json

Dependency Types

  1. dependencies: Production dependencies, required for application runtime
  2. devDependencies: Development dependencies, only needed during development
  3. peerDependencies: Peer dependencies, provided by host project
  4. 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.

标签:NPM