The npm Ecosystem

Last update: 2023-08-03 06:51:10 +0800 +0800
Available translations: 日本語 / 中文(简体) / 中文(繁體)

npm is the package manager distributed with Node.js. It installs packages, runs project scripts, publishes packages to registries, and records dependency resolutions so a team can reproduce an application build.

Package Metadata #

Every npm project is described by package.json. Its most important fields identify the package, define scripts, and declare dependencies:

json
{
  "name": "example-service",
  "private": true,
  "type": "module",
  "scripts": {
    "test": "node --test",
    "start": "node src/server.js"
  },
  "dependencies": {
    "fastify": "^5.0.0"
  },
  "devDependencies": {
    "typescript": "^5.0.0"
  },
  "engines": {
    "node": ">=20"
  }
}

dependencies are needed in production. devDependencies support development, testing, or builds. A package marked private: true cannot accidentally be published.

The type field controls how .js files are interpreted: "module" selects ECMAScript modules and the default CommonJS behavior applies when it is absent. Packages that support both module systems can use the exports field to expose deliberate public entry points.

Version Ranges and Lockfiles #

npm versions follow semantic versioning: major.minor.patch. A caret range such as ^5.2.1 permits compatible minor and patch updates before the next major release; a tilde range such as ~5.2.1 permits patch updates only. Exact versions provide the strictest constraint.

package.json expresses the allowed ranges, while package-lock.json records the exact dependency tree that npm resolved. Commit both for applications and use npm ci in continuous integration. Unlike npm install, npm ci requires the lockfile to match the manifest and installs a clean, frozen tree.

sh
npm install
npm run test
npm ci
npm outdated
npm update

Scripts and Executables #

npm run <script> runs a command from the scripts field and places local executables from node_modules/.bin on PATH. This makes npm run lint portable without requiring a global installation. Pass arguments after --:

sh
npm run test -- --watch

Use npx <package> or npm exec <package> for occasional command execution. Prefer project dependencies and scripts for commands that contributors or CI must run repeatedly.

Registries and Publishing #

The public npm registry is the default, but .npmrc can select a registry for a scope:

ini
@acme:registry=https://registry.example.com/

Authenticate with a token managed outside the repository, especially in CI. Before publishing a library, check files, .npmignore, exports, the license, and the generated tarball:

sh
npm pack --dry-run
npm publish

Libraries should publish only their intended runtime files and document their supported Node.js versions. Applications normally remain private and are deployed rather than published.

Comments

Read or comment on GitHub (sign-in required to comment)