简体   繁体   English

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

[英]How to notify NPM package version update to user?

I have written a CLI tool in Node JS and published to NPM .我在 Node JS 中编写了一个 CLI 工具并发布到NPM Every time it's run in terminal, I need the user to be notified of a new version available and its type (patch | minor | major) so that he/she can update it accordingly.每次在终端中运行时,我都需要通知用户可用的新版本及其类型(补丁 | 次要 | 主要),以便他/她可以相应地更新它。 How can I implement this?我该如何实施?

Moreover, is it possible to ask the user if he/she would like to have the package updated by itself?此外,是否可以询问用户是否希望 package 自行更新?

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

Version Update Check:版本更新检查:

I would suggest using update-notifier but strangely it doesn't work.我建议使用update-notifier但奇怪的是它不起作用。 So, I chose to handle this work by myself.所以,我选择自己来处理这项工作。

The latest version can be checked easily with package-json which fetches the metadata of a package from the npm registry.可以使用package-json轻松检查最新版本,该 package-json 从 npm 注册表中获取 package 的元数据。 Alternatively latest-version can be used as well which uses package-json under the hood.或者,也可以使用最新版本,它在后台使用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',
    }));
  }
};

Update notification:更新通知:

Every time the tool runs, user would see such a notification if an update is available.每次工具运行时,如果有可用更新,用户都会看到这样的通知。

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM