如何通知用户 NPM 包版本更新?

How to notify NPM package version update to user?

我用 Node JS 编写了一个 CLI 工具并发布到 NPM。每次在终端中出现 运行 时,我都需要通知用户可用的新版本及其类型(补丁 | 次要 | 主要),以便 he/she 可以相应地更新它。我该如何实施?

此外,是否可以询问用户he/she是否希望自己更新包?

A new version of Rapid React is available. Would you like to update it now?(Y\n)

版本更新检查:

我建议使用 update-notifier 但奇怪的是它不起作用。所以,我选择了自己来完成这项工作。

可以使用 package-json which fetches the metadata of a package from the npm registry. Alternatively latest-version 轻松检查最新版本,也可以使用 package-json

import boxen from 'boxen';
import chalk from 'chalk';
import semver from 'semver';
import pkgJson from 'package-json';
import semverDiff from 'semver-diff';

import { capitalizeFirstLetter } from '../utils';

import { name, version } from '../../package.json';

const checkUpdate = async () => {
  const { version: latestVersion } = await pkgJson(name);

  // check if local package version is less than the remote version
  const updateAvailable = semver.lt(version, latestVersion as string);

  if (updateAvailable) {
    let updateType = '';

    // check the type of version difference which is usually patch, minor, major etc.
    let verDiff = semverDiff(version, latestVersion as string);

    if (verDiff) {
      updateType = capitalizeFirstLetter(verDiff);
    }

    const msg = {
      updateAvailable: `${updateType} update available ${chalk.dim(version)} → ${chalk.green(latestVersion)}`,
      runUpdate: `Run ${chalk.cyan(`npm i -g ${name}`)} to update`,
    };

    // notify the user about the available udpate
    console.log(boxen(`${msg.updateAvailable}\n${msg.runUpdate}`, {
      margin: 1,
      padding: 1,
      align: 'center',
    }));
  }
};

更新通知:

每次该工具运行时,如果有可用更新,用户会看到这样的通知。