Lessons from opensource: Log "new version is available" to your CLI

Lessons from opensource: Log "new version is available" to your CLI

These lessons are picked from next.js/create-next-app open source code. In this article, you will learn how the CLI logs that a new version of create-next-app is available when there is a new version released.

// The following code snippet is from: 
// https://github.com/vercel/next.js/blob/canary/packages/create-next-app/index.ts#L473

import checkForUpdate from 'update-check'

const update = checkForUpdate(packageJson).catch(() => null)

async function notifyUpdate(): Promise<void> {
  try {
    const res = await update
    if (res?.latest) {
      const updateMessage =
        packageManager === 'yarn'
          ? 'yarn global add create-next-app'
          : packageManager === 'pnpm'
          ? 'pnpm add -g create-next-app'
          : packageManager === 'bun'
          ? 'bun add -g create-next-app'
          : 'npm i -g create-next-app'

      console.log(
        yellow(bold('A new version of `create-next-app` is available!')) +
          '\n' +
          'You can update by running: ' +
          cyan(updateMessage) +
          '\n'
      )
    }
    process.exit()
  } catch {
    // ignore error
  }
}

Subscribe to my newsletter to get more lessons from opensource.

update-check is an npm package, If there’s a new update available, the package will return the content of latest version’s package.json file. Quite simple and powerful.

Conclusion:

Now you know how your CLI notifies whenever there is new release available for your globally installed packages.

If you are looking to improve/learn frontend, checkout my website: https://tthroo.com/ where I teach project based tutorials.