Home » Chalk Module in JavaScript Tutorial with Examples

Chalk Module in JavaScript Tutorial with Examples

Chalk is a popular JavaScript library used to style terminal string output.

It allows you to change text color, background color, and apply styles like bold, italic, and underline, making your console logs more visually appealing and easier to read.

In this tutorial, we will cover:

  1. What is Chalk?
  2. Installation and Setup
  3. Basic Text Styling with Chalk
  4. Combining Multiple Styles
  5. Using Background Colors
  6. Chalk Template Literals
  7. Chalk Level and Support Detection
  8. Examples and Use Cases

Let's dive into each section with examples.

1. What is Chalk?

Chalk is a Node.js package that helps you style text in the terminal by changing the text color, background color, and adding effects like bold, underline, and more.

It's particularly useful for creating clean, readable CLI output.

2. Installation and Setup

You can install Chalk using npm or yarn.

Installation via npm:

npm install chalk

Installation via yarn:

yarn add chalk

Importing Chalk in your project:

const chalk = require('chalk');

// ES6 Import
// import chalk from 'chalk';

3. Basic Text Styling with Chalk

Chalk allows you to apply basic styles to your console output, such as changing the text color to red, green, blue, and more.

Example 1: Changing Text Color

const chalk = require('chalk');

// Using chalk to colorize text
console.log(chalk.red('This is red text!'));
console.log(chalk.green('This is green text!'));
console.log(chalk.blue('This is blue text!'));

Output:

This is red text!
This is green text!
This is blue text!

In this example:

  • chalk.red() applies red color to the text.
  • chalk.green() applies green color to the text.
  • chalk.blue() applies blue color to the text.

4. Combining Multiple Styles

Chalk allows you to combine multiple styles like bold, italic, and underline with colors.

Example: Combining Styles

const chalk = require('chalk');

// Combining multiple styles
console.log(chalk.blue.bold('Bold and Blue!'));
console.log(chalk.red.underline('Underlined Red!'));
console.log(chalk.green.italic('Italic and Green!'));
console.log(chalk.yellow.bold.underline('Bold, Underlined, and Yellow!'));

Output:

Bold and Blue!
Underlined Red!
Italic and Green!
Bold, Underlined, and Yellow!

In this example:

  • chalk.blue.bold() applies both blue color and bold styling.
  • chalk.red.underline() applies red color and underline.
  • chalk.green.italic() applies green color and italic styling.
  • You can chain styles in any combination.

5. Using Background Colors

Chalk also allows you to change the background color of text in addition to the text color.

Example: Applying Background Colors

const chalk = require('chalk');

// Applying background colors
console.log(chalk.white.bgRed('White text with Red background!'));
console.log(chalk.black.bgGreen('Black text with Green background!'));
console.log(chalk.blue.bgYellow('Blue text with Yellow background!'));

Output:

White text with Red background!
Black text with Green background!
Blue text with Yellow background!

In this example:

  • chalk.white.bgRed() sets the text color to white and the background color to red.
  • chalk.black.bgGreen() sets the text color to black and the background color to green.
  • chalk.blue.bgYellow() sets the text color to blue and the background color to yellow.

6. Chalk Template Literals

Chalk supports template literals for more dynamic styling. You can use template literals to inject variables or values directly into styled text.

Example: Chalk with Template Literals

const chalk = require('chalk');

const name = 'John';
const age = 30;

console.log(chalk.green(`Hello, ${name}! You are ${age} years old.`));
console.log(chalk.blue(`Name: ${name}, Age: ${age}`));

Output:

Hello, John! You are 30 years old.
Name: John, Age: 30

In this example:

  • Template literals allow you to insert variables like name and age directly into the string and apply chalk styles to the entire sentence.

7. Chalk Level and Support Detection

Chalk automatically detects the terminal’s color support level, but you can manually control it using the chalk.level property.

Color Levels:

  • 0: All colors are disabled (monochrome output).
  • 1: Basic colors (16 colors).
  • 2: ANSI 256 colors.
  • 3: Truecolor (16 million colors).

Example: Checking and Setting Color Level

const chalk = require('chalk');

// Check current color support level
console.log(`Chalk color support level: ${chalk.level}`);

// Set chalk level to 1 (basic colors)
chalk.level = 1;

console.log(chalk.green('This is basic green (level 1).'));

In this example:

  • chalk.level returns the current color support level.
  • You can manually set chalk.level to control how colors are displayed (e.g., setting it to 1 for basic color support).

8. Examples and Use Cases

Example 1: Creating a Colorful CLI Output

const chalk = require('chalk');

// Simulating a CLI message with various styles
console.log(chalk.yellow('Warning: ') + chalk.red.bold('Low disk space!'));
console.log(chalk.green('Success: ') + 'Data saved successfully.');
console.log(chalk.blue('Info: ') + 'New updates are available.');

Output:

Warning: Low disk space!
Success: Data saved successfully.
Info: New updates are available.

In this example, we simulate common CLI messages with different styles for warnings, success messages, and information.

Example 2: Using Chalk in Loops for Colorful Lists

const chalk = require('chalk');

const fruits = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];

fruits.forEach((fruit, index) => {
    const color = index % 2 === 0 ? chalk.red : chalk.green;
    console.log(color(fruit));
});

Output:

Apple  (red)
Banana (green)
Cherry (red)
Date   (green)
Elderberry (red)

In this example, we alternate colors between red and green when printing a list of fruits.

Example 3: Creating Styled Error Messages

const chalk = require('chalk');

// Simulate an error message
const errorMessage = chalk.bgRed.white.bold(' ERROR ') + chalk.red(' Something went wrong!');
console.log(errorMessage);

Output:

ERROR Something went wrong!

In this example:

  • We use chalk.bgRed.white.bold() to create a visually distinct error message with a red background and bold white text.

Summary of Chalk Key Methods

Method Description Example
chalk.color() Colors the text using a specified color. chalk.red(‘text')
chalk.bgColor() Changes the background color of the text. chalk.bgGreen(‘text')
chalk.bold() Makes the text bold. chalk.bold(‘text')
chalk.italic() Makes the text italic. chalk.italic(‘text')
chalk.underline() Underlines the text. chalk.underline(‘text')
chalk.templateLiterals Supports template literals with styles applied. chalk.green(`Hello, ${name}`)
chalk.level Manually sets the color support level. chalk.level = 1

Conclusion

The Chalk library is a fantastic tool for styling terminal output in JavaScript, allowing you to create colorful, easy-to-read, and styled command-line interfaces. In this tutorial, we covered:

  • Basic text styling like changing text color, background color, and applying bold/underline.
  • Combining multiple styles to create complex visual effects.
  • Using template literals with Chalk to add dynamic content.
  • Controlling color support levels and detecting terminal capabilities.

You may also like