Lessons from open-source: Use picocolors to format terminal output with colors

Lessons from open-source: Use picocolors to format terminal output with colors

This lessson is picked from Next.js source code. In this article, you will learn what a picocolors package is, how Next.js uses it to apply colors to terminal output.

Picocolors

picocolors is the tiniest and the fastest library for terminal output formatting with ANSI colors.

import pc from “picocolors”

console.log(
pc.green(`How are ${pc.italic(`you`)} doing?`)
)

You can read full documentation on Github.

Practice the exercises based on documentation to become an expert in Next.js

How Next.js uses it to apply colors to terminal output?

Surprisingly, Next.js does not have picocolors as a dependency in package.json, because it is so tiny, Next.js authors have picked the picocolors source code and placed it in packages/next/src/lib/picocolors.ts

It is important to mention the license and copyright when you copy open source code. Next.js authors even put the link to the file where this code is picked from.

L19 in the above image has ‘globalThis’. I have seen ‘this’, ‘self,’ ‘window’ but not ‘globalThis’.

globalThis

The globalThis global property contains the global this value, which is usually akin to the global object. — MDN Docs

To access global this value consistently in window and non-window contexts without knowing the environment in which the code is being run, you can use globalThis.

Conclusion:

Picocolors can be used to apply colors to your terminal output. I have found this import in Next.js build command related files. Because this package is so tiny, Next.js authors have picked the picocolors source code and placed it in packages/next/src/lib/picocolors.ts.

I have used ‘this’, ‘self,’ ‘window’ but not ‘globalThis’. Upon further reading the MDN docs, I learnt that to access global ‘this’ javascript context independant of environments (I am talking browser or non-browser environments), ‘globalThis’ can be used.

You learn something new everyday! 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *