Lessons from opensource: Log "new version is available" to your CLI
Ramu Narasinga
Posted on March 2, 2024
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
}
}
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.
Get free courses inspired by the best practices used in open source.
About me:
Website: https://ramunarasinga.com/
Linkedin: https://www.linkedin.com/in/ramu-narasinga-189361128/
Github: https://github.com/Ramu-Narasinga
Email: ramu.narasinga@gmail.com
Posted on March 2, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
June 27, 2024