npm-check-updates vs npm-check vs yarn-upgrade-all
Node.js 依赖版本管理与升级策略深度对比
npm-check-updatesnpm-checkyarn-upgrade-all类似的npm包:

Node.js 依赖版本管理与升级策略深度对比

npm-check、npm-check-updates (ncu) 和 yarn-upgrade-all 都是用于管理 Node.js 项目依赖版本的工具,但它们的核心理念和适用场景截然不同。npm-check 是一个交互式的诊断工具,旨在帮助开发者在升级前可视化地审查依赖状态(过时、未使用、缺失),适合人工决策。npm-check-updates 是一个强大的自动化引擎,专注于批量修改 package.json 中的版本范围,常集成于 CI/CD 流程中实现自动升级。yarn-upgrade-all 则是 Yarn 生态早期的一个辅助脚本,用于强制将所有依赖升级到最新,但因缺乏精细控制和现代 Yarn 版本的演进,目前已不再推荐用于生产环境。

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
npm-check-updates986,14710,3255.56 MB471 个月前Apache-2.0
npm-check191,2116,63294.1 kB232-MIT
yarn-upgrade-all28,093957.77 kB26 个月前MIT

npm-check vs npm-check-updates vs yarn-upgrade-all: 依赖管理工具深度解析

在大型前端工程中,依赖管理不仅仅是运行 npm install。随着项目迭代,依赖包会过时、废弃或产生安全漏洞。npm-check、npm-check-updates (ncu) 和 yarn-upgrade-all 试图解决这一问题,但它们的设计哲学完全不同:一个是交互式诊断器,一个是自动化引擎,另一个则是已过时的暴力升级脚本。让我们深入对比它们在实际工程中的表现。

🔍 核心定位:诊断 vs 自动化 vs 强制升级

npm-check 的核心价值在于可视化诊断。它不会直接修改你的文件,而是提供一个交互式界面,让你看到哪些包过时了、哪些包根本没被使用、哪些包缺失了。

# npm-check: 启动交互式界面
npx npm-check
# 操作:使用空格键选择要更新的包,回车确认

npm-check-updates 的核心价值在于批量修改配置。它直接读取 package.json,将版本范围(如 ^1.0.0)更新为你指定的目标(如最新版),然后你需要自己运行安装命令。

# npm-check-updates: 检查可更新的包
npx npm-check-updates

# 直接修改 package.json 到最新版本
npx npm-check-updates -u

yarn-upgrade-all 的核心逻辑是暴力覆盖。它试图忽略 package.json 中的版本锁定,强制将所有包升级到 registry 上的最新版。这种策略在现代工程中极其危险。

# yarn-upgrade-all: 强制升级所有包 (已不推荐)
npx yarn-upgrade-all

🛠️ 工作流集成:交互操作 vs CI/CD 自动化

在持续集成(CI)环境中,交互性毫无用处,我们需要的是可预测的脚本行为。

npm-check 很难集成到自动化流程中,因为它默认等待用户输入。虽然它有 --ci 模式,但其主要产出是报告而非可执行的更新文件。

# npm-check: 仅生成报告,不修改文件
npx npm-check --ci
# 输出:文本列表,显示哪些包需要更新

npm-check-updates 天生为自动化而生。它可以轻松嵌入 package.json 脚本或 GitHub Actions,自动创建 Pull Request。

// package.json: 集成 ncu 到脚本
{
  "scripts": {
    "dep:check": "ncu",
    "dep:update": "ncu -u && npm install"
  }
}
# GitHub Actions 示例
- name: Upgrade Dependencies
  run: npx npm-check-updates -u && git commit -am "chore: update deps"

yarn-upgrade-all 缺乏细粒度的控制选项,无法配置“忽略某些包”或“只升级补丁版本”,这使得它在自动化流程中极易导致构建失败。

# yarn-upgrade-all: 缺乏过滤参数,只能全量升级
# 无法实现 --exclude 或 --target 等高级控制

🎯 版本控制精度:精细筛选 vs 一刀切

升级依赖最可怕的是引入破坏性变更(Breaking Changes)。工具是否支持精细的版本控制至关重要。

npm-check 允许你在交互界面中为每个包选择具体的版本(最新、稳定版、或特定版本),这种手动控制最安全。

# npm-check: 交互界面中可选
# [ ] lodash  ^4.17.20  →  4.17.21 (Patch)
# [ ] lodash  ^4.17.20  →  5.0.0  (Major - 风险高)
# 用户可手动勾选特定版本

npm-check-updates 提供丰富的命令行参数来控制升级粒度,比如只升级补丁版本(-t patch)或排除特定包。

# ncu: 只升级补丁版本 (最安全)
npx npm-check-updates -t patch -u

# ncu: 排除 react 和 vue,防止大版本误升级
npx npm-check-updates -u --reject react,vue

yarn-upgrade-all 顾名思义,就是“全部升级”。它不提供版本过滤机制,一旦运行,所有依赖(包括大版本变更)都会被强制更新,极易导致项目崩溃。

# yarn-upgrade-all: 无参数可控制版本范围
# 风险:可能直接将 react 16 升级到 react 18,导致构建报错

🗑️ 额外功能:清理无用依赖

除了升级,依赖管理的另一大痛点是清理。

npm-check 是唯一一个内置未使用依赖检测功能的工具。它会分析你的源代码,指出哪些包安装了但从未被 import 或 require。

# npm-check: 检测未使用的包
# 输出示例:
# unused: moment  # 已安装但代码中未使用
# 可以在交互界面直接选择卸载

npm-check-updates 专注于版本更新,不具备代码扫描功能,无法识别未使用的依赖。

# ncu: 仅关注版本号变更
# 不会告诉你哪些包是多余的

yarn-upgrade-all 同样不具备清理功能,甚至可能因为强制升级而引入新的无用依赖树。

⚠️ 维护状态与生态兼容性

工具的活跃度直接决定了它能否支持最新的包管理器特性。

npm-check 目前维护状态良好,支持 npm 和 yarn,适合本地开发环境使用。

npm-check-updates 非常活跃,社区贡献频繁,完美支持 npm、yarn 和 pnpm,是目前的行业标准。

yarn-upgrade-all 已停止维护。随着 Yarn Berry (v2/v3/v4) 的推出,其插件架构发生了根本性变化,该工具已不再兼容现代 Yarn 版本。Yarn 官方现在推荐使用原生的 yarn up 命令。

# 现代 Yarn 的正确做法 (替代 yarn-upgrade-all)
yarn up '*' --mode=skip-range

📊 总结对比表

特性npm-checknpm-check-updatesyarn-upgrade-all
核心用途交互式诊断与清理自动化版本更新强制全量升级 (已过时)
修改文件可选 (交互确认)是 (直接修改 package.json)是 (直接修改)
CI/CD 友好低 (需交互)高 (纯命令行)中 (但风险高)
版本控制手动选择每个包支持 patch/minor/major 过滤无 (强制最新)
无用检测✅ 支持❌ 不支持❌ 不支持
维护状态✅ 活跃✅ 非常活跃❌ 已废弃

💡 架构师建议

在现代前端工程架构中,我们建议采用组合策略:

  1. 本地开发阶段:使用 npm-check。在开始一个大版本重构前,运行它来识别并删除未使用的依赖,减少打包体积。通过交互界面安全地升级关键库。
  2. 自动化运维阶段:使用 npm-check-updates。将其配置在 GitHub Actions 或 GitLab CI 中,每周自动运行一次 ncu -t patch(仅补丁升级),并自动提交 PR。对于大版本升级,则人工运行 ncu 进行审查。
  3. 避坑指南:彻底弃用 yarn-upgrade-all。如果你在使用 Yarn,请迁移到 yarn up 命令。不要在一个成熟的项目中运行“无条件全部升级”,这违背了稳定优先的工程原则。

最终结论:npm-check-updates 是自动化流程的王者,npm-check 是本地清理的神器,而 yarn-upgrade-all 应留在历史的尘埃中。

如何选择: npm-check-updates vs npm-check vs yarn-upgrade-all

  • npm-check-updates:

    当你需要自动化升级流程或精确控制版本范围时选择 npm-check-updates。它是 CI/CD 流水线的理想选择,支持通过配置文件忽略特定包,并能灵活地将依赖升级到最新、最新稳定版或仅修补版本。

  • npm-check:

    当你需要人工审查依赖状况时选择 npm-check。它适合在重构前识别未使用的包,或在升级前通过交互式界面逐个确认版本,避免自动化脚本误删关键依赖。它的优势在于“诊断”而非“执行”。

  • yarn-upgrade-all:

    不建议在新项目中使用 yarn-upgrade-all。该工具已停止维护,且其“全部强制升级”的策略风险极高,容易引入破坏性变更。现代 Yarn (v2+) 用户应直接使用原生的 yarn up 命令替代。

npm-check-updates的README

npm-check-updates

npm version Build Status

npm-check-updates upgrades your package.json dependencies to the latest versions, ignoring specified versions.

  • maintains existing semantic versioning policies, i.e. "react": "^18.3.1" to "react": "^19.2.7".
  • only modifies package.json file. Run npm install to update your installed packages and package-lock.json.
  • sensible defaults, but highly customizable
  • compatible with npm, yarn, pnpm, deno, and bun
  • CLI and module usage
  • Pure ESM, also usable from CommonJS via require()
ncu example output

$${\color{red}Red}$$ major upgrade (and all major version zero)
$${\color{cyan}Cyan}$$ minor upgrade
$${\color{green}Green}$$ patch upgrade

Requirements

  • Node.js: ^22.22.2 || ^24.15.0 || >=26.0.0
  • npm: >=10.0.0

Installation

Install globally to use npm-check-updates or the shorter ncu:

npm install -g npm-check-updates

Or run with npx (only the long form is supported):

npx npm-check-updates

Usage

Check the latest versions of all project dependencies:

$ ncu
Checking package.json
[====================] 5/5 100%

 eslint             7.32.0  →    8.0.0
 prettier           ^2.7.1  →   ^3.0.0
 svelte            ^3.48.0  →  ^3.51.0
 typescript         >3.0.0  →   >4.0.0
 untildify          <4.0.0  →   ^4.0.0
 webpack               4.x  →      5.x

Run ncu -u to upgrade package.json

Upgrade a project's package file:

Make sure your package file is in version control and all changes have been committed. This will overwrite your package file.

$ ncu -u
Upgrading package.json
[====================] 1/1 100%

 express           4.12.x  →   4.13.x

Run npm install to install new versions.

$ npm install      # update installed packages and package-lock.json

Check global packages:

ncu -g

Interactive Mode

Choose which packages to update in interactive mode:

ncu --interactive
ncu -i

ncu --interactive

Combine with --format group for a truly luxe experience:

ncu --interactive --format group

Keys

  • ↑↓ Select a package
  • Space Toggle selection
  • a Toggle all
  • Enter Upgrade

Pre-selected upgrades

ncu -i pre-selects patch and minor upgrades, since --format group is enabled by default. Only when group formatting is disabled with --format no-group are all upgrades pre-selected, including major. Use --interactiveSelect to control this explicitly:

# start with nothing selected
ncu -i --interactiveSelect none

# pre-select patch upgrades only
ncu -i --interactiveSelect patch

# pre-select patch and minor upgrades
ncu -i --interactiveSelect minor

# pre-select everything, including major
ncu -i --interactiveSelect all

# the default: patch and minor with --format group, everything otherwise
# specify it explicitly to override a value set in your config file
ncu -i --interactiveSelect auto

Major version zero upgrades (e.g. 0.1.0 → 0.2.0) are only pre-selected by all, since anything may change before 1.0.0. Custom groups returned by --groupFunction are likewise only pre-selected by all.

Filter packages

Filter packages using the --filter option or adding additional cli arguments:

# upgrade only mocha
ncu mocha
ncu -f mocha
ncu --filter mocha

# upgrade only chalk, mocha, and react
ncu chalk mocha react
ncu chalk, mocha, react
ncu -f "chalk mocha react"

Filter with wildcards or regex:

# upgrade packages that start with "react-"
ncu react-*
ncu "/^react-.*$/"

Exclude specific packages with the --reject option or prefixing a filter with !. Supports strings, wildcards, globs, comma-or-space-delimited lists, and regex:

# upgrade everything except nodemon
ncu \!nodemon
ncu -x nodemon
ncu --reject nodemon

# upgrade packages that do not start with "react-".
ncu \!react-*
ncu '/^(?!react-).*$/' # mac/linux
ncu "/^(?!react-).*$/" # windows

Advanced filters: filter, filterResults, filterVersion

How dependency updates are determined

  • Direct dependencies are updated to the latest stable version:
    • 2.0.1 → 2.2.0
    • 1.2 → 1.3
    • 0.1.0 → 1.0.1
  • Range operators are preserved and the version is updated:
    • ^1.2.0 → ^2.0.0
    • 1.x → 2.x
    • >0.2.0 → >0.3.0
  • "Less than" is replaced with a wildcard:
    • <2.0.0 → ^3.0.0
    • 1.0.0 < 2.0.0 → ^3.0.0
  • "Any version" is preserved:
    • * → *
  • Prerelease versions are ignored by default.
    • Use --pre to include prerelease versions (e.g. alpha, beta, build1235)
  • Choose what level to upgrade to:
    • With --target semver, update according to your specified semver version ranges:
      • ^1.1.0 → ^1.9.99
      • An explicit upper bound is respected and preserved, so the upgrade never exceeds it:
        • ^9.5.0 <10 → ^9.7.0 <10
    • With --target minor, strictly update the patch and minor versions (including major version zero):
      • 0.1.0 → 0.2.1
    • With --target patch, strictly update the patch version (including major version zero):
      • 0.1.0 → 0.1.2
    • With --target @next, update to the version published on the next tag:
      • 0.1.0 -> 0.1.1-next.1

Options

Options are merged with the following precedence:

  1. Command line options
  2. Local Config File (current working directory)
  3. Project Config File (next to package.json)
  4. User Config File ($HOME)

Options that take no arguments can be negated by prefixing them with --no-, e.g. --no-peer.

--cacheCache versions to a local cache file. Default --cacheFile is ~/.ncu-cache.json and default --cacheExpiration is 10 minutes.
--cacheClearClear the default cache, or the cache file specified by --cacheFile.
--cacheExpiration <min>Cache expiration in minutes. Only works with --cache. (default: 10)
--cacheFile <path>Filepath for the cache file. Only works with --cache. (default: "~/.ncu-cache.json")
--colorForce color in terminal.
--concurrency <n>Max number of concurrent HTTP requests to registry. (default: 8)
--configFileName <s>Config file name. (default: .ncurc or .ncurc.{json,yaml,yml,js,mjs,cjs})
--configFilePath <path>Directory of .ncurc config file. (default: directory of packageFile)
-c, --cooldown <period>Sets a minimum age for package versions to be considered for upgrade. Accepts a number (days) or a string with a unit: "7d" (days), "12h" (hours), "30m" (minutes). Reduces the risk of installing newly published, potentially compromised packages.
--cwd <path>Working directory in which npm will be executed.
--deepRun recursively in current working directory. Alias of (--packageFile '**/package.json').
--dep <value>Check one or more sections of dependencies only: dev, optional, peer, prod, packageManager, or devEngines (comma-delimited). (default: ["prod","dev","optional","packageManager"])
--deprecatedInclude deprecated packages. Use --no-deprecated to exclude deprecated packages. (default: true)
-d, --doctorIteratively installs upgrades and runs tests to identify breaking upgrades. Requires -u to execute.
--doctorInstall <command>Specifies the install script to use in doctor mode. (default: npm install or the equivalent for your package manager)
--doctorTest <command>Specifies the test script to use in doctor mode. (default: npm test)
--enginesNodeInclude only packages that satisfy engines.node as specified in the package file.
-e, --errorLevel <n>Set the error level. 1: exits with error code 0 if no errors occur. 2: exits with error code 0 if no packages need updating (useful for continuous integration). (default: 1)
-f, --filter <p>Include only package names matching the given string, wildcard, glob, comma-or-space-delimited list, /regex/, or predicate function.
filterResults <fn>Filters results based on a user provided predicate function after fetching new versions.
--filterVersion <p>Filter on package version using comma-or-space-delimited list or /regex/.
--format <value>Modify the output formatting or show additional information. Specify one or more comma-delimited values: dep, group, ownerChanged, repo, time, lines, installedVersion, cooldown. group is the only value included by default; use --format no-group to disable it. (default: ["group"])
-g, --globalCheck global packages instead of in the current project.
groupFunction <fn>Customize how packages are divided into groups when using --format group.
--install <value>Control the auto-install behavior: always, never, prompt. (default: "prompt")
-i, --interactiveEnable interactive prompts for each dependency; implies -u unless one of the json options are set.
--interactiveSelect <value>Control which upgrades are pre-selected in interactive mode: auto, none, patch, minor, all. Only applies with --interactive. (default: "auto")
-j, --jsonAllOutput new package file instead of human-readable message.
--jsonDepsLike jsonAll but only lists dependencies, devDependencies, optionalDependencies, etc of the new package data.
--jsonUpgradedOutput upgraded dependencies in json.
-l, --loglevel <n>Amount to log: silent, error, minimal, warn, info, verbose, silly. (default: "warn")
--mergeConfigMerges nested configs with the root config file for --deep or --packageFile options. (default: false)
-m, --minimalDo not upgrade newer versions that are already satisfied by the version range according to semver.
--packageData <value>Package file data (you can also use stdin).
--packageFile <path|glob>Package file(s) location. (default: ./package.json)
-p, --packageManager <s>npm, yarn, pnpm, deno, bun, staticRegistry (default: npm).
--peerCheck peer dependencies of installed packages and filter updates to compatible versions.
--pre <n>Include prerelease versions, e.g. -alpha.0, -beta.5, -rc.2. Automatically set to 1 when --target is newest or greatest, or when the current version is a prerelease. (default: 0)
--prefix <path>Current working directory of npm.
-r, --registry <uri>Specify the registry to use when looking up package versions.
--registryType <type>Specify whether --registry refers to a full npm registry or a simple JSON file or url: npm, json. (default: npm)
-x, --reject <p>Exclude packages matching the given string, wildcard, glob, comma-or-space-delimited list, /regex/, or predicate function.
--rejectVersion <p>Exclude package.json versions using comma-or-space-delimited list or /regex/.
--removeRangeRemove version ranges from the final package version.
--retry <n>Number of times to retry failed requests for package info. (default: 3)
--rootRuns updates on the root project in addition to specified workspaces. Only allowed with --workspace or --workspaces. (default: true)
-s, --silentDon't output anything. Alias for --loglevel silent.
--stdinRead package.json from stdin.
-t, --target <value>Determines the version to upgrade to: latest, newest, greatest, minor, patch, semver, @[tag], or [function]. (default: latest)
--timeout <ms>Global timeout in milliseconds. (default: no global timeout and 30 seconds per npm-registry-fetch)
-u, --upgradeOverwrite package file with upgraded versions instead of just outputting to console.
--verboseLog additional information for debugging. Alias for --loglevel verbose.
--workspace <s>Run on one or more specified workspaces. Add --no-root to exclude the root project. (default: [])
-w, --workspacesRun on all workspaces. Add --no-root to exclude the root project.

Advanced Options

Some options have advanced usage, or allow per-package values by specifying a function in your .ncurc.js file.

Run ncu --help [OPTION] to view advanced help for a specific option, or see below:

cooldown

Usage:

ncu --cooldown [period]
ncu -c [period]

The cooldown option helps protect against supply chain attacks by requiring package versions to be published at least the given amount of time before considering them for upgrade.

The value can be a plain number (days) or a string with a unit suffix:

--cooldown 7       7 days
--cooldown 7d      7 days (same as above)
--cooldown 12h     12 hours
--cooldown 30m     30 minutes

With the default --target latest, if the latest dist-tag version is within the cooldown window, ncu falls back to the greatest version that passes the cooldown threshold. To instead skip the package entirely (strict behaviour), use --target "@latest".

Example:

Let's examine how cooldown works with a package that has these versions available:

1.0.0          Released 7 days ago    (initial version)
1.1.0          Released 6 days ago    (minor update)
1.1.1          Released 5 days ago    (patch update)
1.2.0          Released 5 days ago    (minor update)
2.0.0-beta.1   Released 5 days ago    (beta release)
1.2.1          Released 4 days ago    (patch update)
1.3.0          Released 4 days ago    (minor update) [latest]
2.0.0-beta.2   Released 3 days ago    (beta release)
2.0.0-beta.3   Released 2 days ago    (beta release) [beta]

With default target (latest):

ncu --cooldown 5

Falls back to 1.2.0 because:

  • Latest version (1.3.0) is only 4 days old (within 5-day cooldown)
  • 1.2.0 is the greatest version that is at least 5 days old

With @latest strict target:

ncu --cooldown 5 --target @latest

No update will be suggested because:

  • Latest version (1.3.0) is only 4 days old
  • Cooldown requires versions to be at least 5 days old
  • @latest is strict: no fallback to older versions

With @beta/@tag target:

ncu --cooldown 3 --target @beta

No update will be suggested because:

  • Current beta (2.0.0-beta.3) is only 2 days old
  • Cooldown requires versions to be at least 3 days old
  • Use --cooldown 2 or lower to allow this update

With other targets:

ncu --cooldown 5 --target greatest|newest|minor|patch|semver

Each target will select the best version that is at least 5 days old:

greatest → 1.2.0        (highest version number outside cooldown)
newest   → 2.0.0-beta.1 (most recently published version outside cooldown)
minor    → 1.2.0        (highest minor version outside cooldown)
patch    → 1.1.1        (highest patch version outside cooldown)

You can also provide a custom function in your .ncurc.js file or when importing npm-check-updates as a module.

⚠️ The predicate function is only available in .ncurc.js or when importing npm-check-updates as a module, not on the command line. To convert a JSON config to a JS config, follow the instructions at Config Functions.

/** Set cooldown to 3 days but skip it for `@my-company` packages.
  @param packageName     The name of the dependency.
  @returns               Cooldown days restriction for given package.
*/
cooldown: packageName => (packageName.startsWith('@my-company') ? 0 : 3)

Package Manager Configurations

If --cooldown is not set explicitly, ncu automatically reads the cooldown configuration from your package manager's own native config — each package manager only consults its own config and these are not cross-applied between package managers:

npmReads min-release-age from .npmrc, excluding packages matched by min-release-age-exclude.
yarnReads npmMinimalAgeGate from .yarnrc.yml, excluding packages matched by npmPreapprovedPackages.
pnpmReads minimumReleaseAge from pnpm-workspace.yaml, excluding packages matched by minimumReleaseAgeExclude.

Cooldown Formatting

When using --format cooldown alongside the --cooldown option, ncu will show a list of packages that were skipped due to the --cooldown threshold.

Example:

$ ncu --format cooldown --cooldown 7
Skipped due to 7-day cooldown
 @typescript-eslint/parser  ^8.50.0  →  ^8.59.1      5 days ago
 eslint                     ^10.0.1  →  ^10.3.0      1 day ago

doctor

Usage:

ncu --doctor -u
ncu --no-doctor
ncu -du

Iteratively installs upgrades and runs your project's tests to identify breaking upgrades. Reverts broken upgrades and updates package.json with working upgrades.

Requires -u to execute (modifies your package file, lock file, and node_modules)

To be more precise:

  1. Runs npm install and npm test to ensure tests are currently passing.
  2. Runs ncu -u to optimistically upgrade all dependencies.
  3. If tests pass, hurray!
  4. If tests fail, restores package file and lock file.
  5. For each dependency, install upgrade and run tests.
  6. Prints broken upgrades with test error.
  7. Saves working upgrades to package.json.

Additional options:

--doctorInstallspecify a custom install script (default: npm install or yarn)
--doctorTestspecify a custom test script (default: npm test)

Example:

$ ncu --doctor -u
Running tests before upgrading
npm install
npm run test
Upgrading all dependencies and re-running tests
ncu -u
npm install
npm run test
Tests failed
Identifying broken dependencies
npm install
npm install --no-save [email protected]
npm run test
  ✓ react 15.0.0 → 16.0.0
npm install --no-save [email protected]
npm run test
  ✗ react-redux 6.0.0 → 7.0.0

/projects/myproject/test.js:13
  throw new Error('Test failed!')
  ^

npm install --no-save [email protected]
npm run test
  ✓ react-dnd 10.0.0 → 11.1.3
Saving partially upgraded package.json

filter

Usage:

ncu --filter [p]
ncu -f [p]

Include only package names matching the given string, wildcard, glob, comma-or-space-delimited list, /regex/, or predicate function. Only included packages will be checked with --peer.

--filter runs before new versions are fetched, in contrast to --filterResults which runs after.

You can also specify a custom function in your .ncurc.js file, or when importing npm-check-updates as a module.

⚠️ The predicate function is only available in .ncurc.js or when importing npm-check-updates as a module, not on the command line. To convert a JSON config to a JS config, follow the instructions at Config Functions.

/**
  @param name     The name of the dependency.
  @param semver   A parsed Semver array of the current version.
    (See: https://git.coolaj86.com/coolaj86/semver-utils.js#semverutils-parse-semverstring)
  @returns        True if the package should be included, false if it should be excluded.
*/
filter: (name, semver) => {
  if (name.startsWith('@myorg/')) {
    return false
  }
  return true
}

filterResults

Filters results based on a user provided predicate function after fetching new versions.

filterResults runs after new versions are fetched, in contrast to filter, reject, filterVersion, and rejectVersion, which run before. This allows you to exclude upgrades with filterResults based on how the version has changed (e.g. a major version change).

⚠️ The predicate function is only available in .ncurc.js or when importing npm-check-updates as a module, not on the command line. To convert a JSON config to a JS config, follow the instructions at Config Functions.

/** Exclude major version updates. Note this could also be achieved with --target semver.
  @param {string} packageName               The name of the dependency.
  @param {string} current                   Current version declaration (may be a range).
  @param {SemVer[]} currentVersionSemver    Current version declaration in semantic versioning format (may be a range).
  @param {string} upgraded                  Upgraded version.
  @param {SemVer} upgradedVersionSemver     Upgraded version in semantic versioning format.
  @returns {boolean}                        Return true if the upgrade should be kept; otherwise, it will be ignored.
*/
filterResults: (packageName, { current, currentVersionSemver, upgraded, upgradedVersionSemver }) => {
  const currentMajor = parseInt(currentVersionSemver[0]?.major, 10)
  const upgradedMajor = parseInt(upgradedVersionSemver?.major, 10)
  if (currentMajor && upgradedMajor) {
    return currentMajor >= upgradedMajor
  }
  return true
}

For the SemVer type definition, see: https://git.coolaj86.com/coolaj86/semver-utils.js#semverutils-parse-semverstring

filterVersion

Usage:

ncu --filterVersion [p]

Include only versions matching the given string, wildcard, glob, comma-or-space-delimited list, or /regex/.

--filterVersion runs before new versions are fetched, in contrast to --filterResults which runs after.

To filter with a predicate function, use filter instead. It receives the package name and the parsed current version, so it can match on both name and version.

format

Usage:

ncu --format [value]

Default: group

Modify the output formatting or show additional information. Specify one or more comma-delimited values.

depPrints the dependency type (dev, peer, optional) of each package.
groupGroups packages by major, minor, patch, and major version zero updates.
homepageDisplays links to the package's homepage if specified in its package.json.
installedVersionPrints the exact current version number instead of a range.
linesPrints name@version on separate lines. Useful for piping to npm install.
ownerChangedShows if the package owner has changed.
repoInfers and displays links to the package's source code repository. Requires packages to be installed.
diffDisplay link to compare the changes between package versions.
timeShows the publish time of each upgrade.
cooldownShows a list of packages that were skipped due to the --cooldown threshold.

group is the only value included by default. Prefix it with "no-" to remove it instead of replacing the entire list, e.g. --format no-group to disable the default grouping.

groupFunction

Customize how packages are divided into groups when using --format group.

Only available in .ncurc.js or when importing npm-check-updates as a module, not on the command line. To convert a JSON config to a JS config, follow the instructions at Config Functions.

/**
  @param name             The name of the dependency.
  @param defaultGroup     The predefined group name which will be used by default.
  @param currentSpec      The current version range in your package.json.
  @param upgradedSpec     The upgraded version range that will be written to your package.json.
  @param upgradedVersion  The upgraded version number returned by the registry.
  @returns                A predefined group name ('major' | 'minor' | 'patch' | 'majorVersionZero' | 'none') or a custom string to create your own group.
*/
groupFunction: (name, defaultGroup, currentSpec, upgradedSpec, upgradedVersion) => {
  if (name === 'typescript' && defaultGroup === 'minor') {
    return 'major'
  }
  if (name.startsWith('@myorg/')) {
    return 'My Org'
  }
  return defaultGroup
}

install

Usage:

ncu --install [value]

Default: prompt

Control the auto-install behavior.

alwaysRuns your package manager's install command automatically after upgrading.
neverDoes not install and does not prompt.
promptShows a message after upgrading that recommends an install, but does not install. In interactive mode, prompts for install. (default)

interactiveSelect

Usage:

ncu --interactiveSelect [value]

Default: auto

Control which upgrades are pre-selected in interactive mode. Only applies with --interactive.

autoPre-selects patch and minor upgrades with --format group, which is enabled by default, and all upgrades otherwise. This is what ncu -i does. (default)
noneNothing is pre-selected.
patchPatch upgrades are pre-selected.
minorPatch and minor upgrades are pre-selected.
allAll upgrades are pre-selected, including major.

Specify auto explicitly to restore the default when another value is set in your config file.

Major version zero upgrades (e.g. 0.1.0 → 0.2.0) are only pre-selected by all, since anything may change before 1.0.0. Custom groups returned by --groupFunction are likewise only pre-selected by all.

packageManager

Usage:

ncu --packageManager [s]
ncu -p [s]

Specifies the package manager to use when looking up versions.

npmSystem-installed npm. Default.
yarnSystem-installed yarn. Automatically used if yarn.lock is present.
pnpmSystem-installed pnpm. Automatically used if pnpm-lock.yaml is present.
bunSystem-installed bun. Automatically used if bun.lock or bun.lockb is present.

peer

Usage:

ncu --peer
ncu --no-peer

Check peer dependencies of installed packages and filter updates to compatible versions.

Example:

The following example demonstrates how --peer works, and how it uses peer dependencies from upgraded modules.

The package ncu-test-peer-update has two versions published:

  • 1.0.0 has peer dependency "ncu-test-return-version": "1.0.x"
  • 1.1.0 has peer dependency "ncu-test-return-version": "1.1.x"

Our test app has the following dependencies:

"ncu-test-peer-update": "1.0.0",
"ncu-test-return-version": "1.0.0"

The latest versions of these packages are:

"ncu-test-peer-update": "1.1.0",
"ncu-test-return-version": "2.0.0"

With --peer:

ncu upgrades packages to the highest version that still adheres to the peer dependency constraints:

ncu-test-peer-update     1.0.0  →  1.1.0
ncu-test-return-version  1.0.0  →  1.1.0

Without --peer:

As a comparison: without using the --peer option, ncu will suggest the latest versions, ignoring peer dependencies:

ncu-test-peer-update     1.0.0  →  1.1.0
ncu-test-return-version  1.0.0  →  2.0.0

registryType

Usage:

ncu --registryType [type]

Specify whether --registry refers to a full npm registry or a simple JSON file.

npmDefault npm registry
jsonChecks versions from a file or url to a simple JSON registry. Must include the --registry option.

Example:

# local file
ncu --registryType json --registry ./registry.json

# url
ncu --registryType json --registry https://api.mydomain/registry.json

# you can omit --registryType when the registry ends in .json
ncu --registry ./registry.json
ncu --registry https://api.mydomain/registry.json

registry.json:

{
  "prettier": "2.7.1",
  "typescript": "4.7.4"
}

reject

Usage:

ncu --reject [p]
ncu -x [p]

The inverse of --filter. Exclude package names matching the given string, wildcard, glob, comma-or-space-delimited list, /regex/, or predicate function. This will also exclude them from the --peer check.

--reject runs before new versions are fetched, in contrast to --filterResults which runs after.

You can also specify a custom function in your .ncurc.js file, or when importing npm-check-updates as a module.

⚠️ The predicate function is only available in .ncurc.js or when importing npm-check-updates as a module, not on the command line. To convert a JSON config to a JS config, follow the instructions at Config Functions.

/**
  @param name     The name of the dependency.
  @param semver   A parsed Semver array of the current version.
    (See: https://git.coolaj86.com/coolaj86/semver-utils.js#semverutils-parse-semverstring)
  @returns        True if the package should be excluded, false if it should be included.
*/
reject: (name, semver) => {
  if (name.startsWith('@myorg/')) {
    return true
  }
  return false
}

rejectVersion

Usage:

ncu --rejectVersion [p]

The inverse of --filterVersion. Exclude versions matching the given string, wildcard, glob, comma-or-space-delimited list, or /regex/.

--rejectVersion runs before new versions are fetched, in contrast to --filterResults which runs after.

To reject with a predicate function, use reject instead. It receives the package name and the parsed current version, so it can match on both name and version.

target

Usage:

ncu --target [value]
ncu -t [value]

Determines the version to upgrade to. (default: "latest")

greatestUpgrade to the highest version number published, regardless of release date or tag. Includes prereleases.
latestUpgrade to whatever the package's "latest" dist-tag points to. When used with --cooldown, falls back to the greatest version that passes the cooldown threshold if the latest is too recent. Use --target "@latest" for strict behaviour that skips the package instead. Excludes prereleases unless --pre is specified.
minorUpgrade to the highest minor version without bumping the major version.
newestUpgrade to the version with the most recent publish date, even if there are other version numbers that are higher. Includes prereleases.
patchUpgrade to the highest patch version without bumping the minor or major versions.
semverUpgrade to the highest version within the semver range specified in your package.json.
@[tag]Upgrade to the version published to a specific tag, e.g. 'next' or 'beta'.

e.g.

ncu --target semver

You can also specify a custom function in your .ncurc.js file, or when importing npm-check-updates as a module.

⚠️ The predicate function is only available in .ncurc.js or when importing npm-check-updates as a module, not on the command line. To convert a JSON config to a JS config, follow the instructions at Config Functions.

/** Upgrade major version zero to the next minor version, and everything else to latest.
  @param name     The name of the dependency.
  @param semver   A parsed Semver object of the upgraded version.
    (See: https://git.coolaj86.com/coolaj86/semver-utils.js#semverutils-parse-semverstring)
  @returns        One of the valid target values (specified in the table above).
*/
target: (name, semver) => {
  if (parseInt(semver[0]?.major) === '0') return 'minor'
  return 'latest'
}

Config File

Add a .ncurc or .ncurc.{json,yaml,yml,js,mjs,cjs} file to your project directory to specify configuration information.

.ncurc without an extension can be in JSON or YAML format. For example:

.ncurc:

upgrade: true
filter: svelte
reject:
  - '@types/estree'
  - ts-node

.ncurc.json:

{
  "upgrade": true,
  "filter": "svelte",
  "reject": ["@types/estree", "ts-node"]
}

Options are merged with the following precedence:

  1. Command line options
  2. Local Config File (current working directory)
  3. Project Config File (next to package.json)
  4. User Config File ($HOME)

You can also specify a custom config file name or path using the --configFileName or --configFilePath command line options.

Config Functions

Some options offer more advanced configuration using a function definition. These include filter, filterVersion, filterResults, reject, rejectVersion, and groupFunction. To define these, use a JavaScript-based configuration file.

ESM (Recommended)

Rename your config to .ncurc.js (if using "type": "module") or .ncurc.mjs.

import { defineConfig } from 'npm-check-updates'

export default defineConfig({
  upgrade: true,
  filter: name => name.startsWith('@myorg/'),
})

CommonJS

Use the .ncurc.cjs extension or a standard .ncurc.js file (if useing "type": "commonjs").

const { defineConfig } = require('npm-check-updates')

module.exports = defineConfig({
  upgrade: true,
  filter: name => name.startsWith('@myorg/'),
})

Alternatively, if you prefer not to use the helper, you can use JSDoc for IntelliSense:

ESM (JSDoc)

/** @type {import('npm-check-updates').RcOptions} */
export default {
  upgrade: true,
  filter: name => name.startsWith('@myorg/'),
}

CommonJS (JSDoc)

/** @type {import('npm-check-updates').RcOptions} */
module.exports = {
  upgrade: true,
  filter: name => name.startsWith('@myorg/'),
}

JSON Schema

If you write .ncurc config files using json or yaml, you can add the JSON Schema to your IDE settings for completions.

e.g. for VS Code:

{
  "json.schemas": [
    {
      "fileMatch": [".ncurc", ".ncurc.json"],
      "url": "https://raw.githubusercontent.com/raineorshine/npm-check-updates/main/src/types/RunOptions.json",
    },
  ],
  "yaml.schemas": {
    "https://raw.githubusercontent.com/raineorshine/npm-check-updates/main/src/types/RunOptions.json": [".ncurc.yml"],
  },
}

Module/Programmatic Usage

npm-check-updates can be imported as a module in both ESM and CommonJS environments.

ESM (Recommended)

Use this for modern projects using "type": "module" in package.json or .mjs files.

import ncu from 'npm-check-updates'

const upgraded = await ncu({
  // Pass any cli option
  packageFile: '../package.json',
  upgrade: true,
  // Defaults:
  // jsonUpgraded: true,
  // silent: true,
})

console.log(upgraded) // { "mypackage": "^2.0.0", ... }

CommonJS

Use this for legacy projects using "type": "commonjs" or scripts using the .cjs extension.

const { default: ncu } = require('npm-check-updates')

// ncu() is an async function
ncu({
  packageFile: './package.json',
  upgrade: true,
}).then(upgraded => {
  console.log(upgraded)
})

Contributing

Contributions are happily accepted. I respond to all PR's and can offer guidance on where to make changes. For contributing tips see CONTRIBUTING.md.

Problems?

File an issue. Please search existing issues first.

License

Apache-2.0