【问题标题】:How to notify NPM package version update to user?如何通知用户 NPM 包版本更新?
【发布时间】:2020-12-24 19:00:39
【问题描述】:

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

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

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

【问题讨论】:

    标签: node.js npm command-line-interface npm-install versioning


    【解决方案1】:

    版本更新检查:

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

    可以使用package-json 轻松检查最新版本,该package-json 从 npm 注册表中获取包的元数据。或者,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',
        }));
      }
    };
    

    更新通知:

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

    【讨论】:

      猜你喜欢
      • 2019-03-28
      • 2019-04-15
      • 1970-01-01
      • 2016-05-18
      • 2018-07-31
      • 1970-01-01
      • 2017-11-06
      • 2012-08-10
      • 2017-02-02
      相关资源
      最近更新 更多