Back

Elevate Your CLI Tools with @clack/prompts

Introduction

@clack/prompts is a robust and versatile library designed for creating command-line interface (CLI) prompts. With a modern design and developer-friendly API, it simplifies the task of building interactive CLI tools by providing a suite of well-thought-out prompt utilities. Whether you're asking a simple yes/no question or designing a multi-step interactive workflow, @clack/prompts streamlines the process while ensuring a polished user experience.

This article delves into the features, use cases, and examples of @clack/prompts to help you get started quickly and effectively.


Key Features

1. Declarative API

The library provides a declarative API that simplifies the creation and management of CLI prompts.

2. Support for Multiple Input Types

@clack/prompts supports various prompt types, including:

  • Text inputs
  • Select menus
  • Confirmation dialogs

3. Asynchronous Workflow

It seamlessly integrates with asynchronous programming patterns, making it suitable for dynamic or data-dependent prompts.

4. Built-in Validations

Customizable validation rules ensure users input valid responses.

5. Extensibility

You can extend and customize prompts to suit unique requirements by integrating them with other libraries or building additional UI layers.


Installation

To use @clack/prompts, install the package using npm or yarn or bun:

npm install @clack/prompts
# or
yarn add @clack/prompts
# or
bun install @clack/prompts

Basic Example

Here's a basic example to illustrate how to use @clack/prompts:

import { select, text, confirm } from '@clack/prompts';

(async () => {
  // Step 1: Ask for a name
  const name = await text({
    message: 'What is your name?'
  });

  // Step 2: Select an option
  const role = await select({
    message: 'Choose your role:',
    options: [
      { label: 'Developer', value: 'dev' },
      { label: 'Designer', value: 'designer' },
      { label: 'Manager', value: 'manager' }
    ]
  });

  // Step 3: Confirmation
  const confirmed = await confirm({
    message: `Confirm your choices: Name = ${name}, Role = ${role}`
  });

  if (confirmed) {
    console.log('Prompt sequence completed successfully!');
  } else {
    console.log('Prompt sequence aborted.');
  }
})();

Advanced Usage

1. Validations

You can define validation rules to ensure the input is in the desired format:

const email = await text({
  message: 'Enter your email address:',
  validate: (value) => (/.+@.+\..+/.test(value) ? true : 'Invalid email format')
});

2. Handling Interrupts

Gracefully handle user interrupts or cancellations by listening to specific events or exceptions:

try {
  const result = await text({
    message: 'Enter something important:'
  });

  if (!result) {
    throw new Error('You must enter something important!');
  }
} catch (err) {
  console.error('Prompt was interrupted.');
}

3. Combining Prompts

Compose multiple prompts to build a more complex CLI flow:

import { text, select } from '@clack/prompts';

async function userDetailsFlow() {
  const name = await text({
    message: 'What is your name?'
  });

  const profession = await select({
    message: 'Select your profession:',
    options: [
      { label: 'Doctor', value: 'doctor' },
      { label: 'Engineer', value: 'engineer' },
      { label: 'Artist', value: 'artist' }
    ]
  });

  return { name, profession };
}

(async () => {
  const user = await userDetailsFlow();
  console.log(`Welcome, ${user.name}, the ${user.profession}!`);
})();

Why Use @clack/prompts?

  • Ease of Use: Developers can quickly set up interactive CLI tools with minimal boilerplate code.
  • Flexibility: From single prompts to multi-step workflows, it supports a wide range of use cases.
  • Customizability: Validation, error handling, and option customization make it adaptable for complex workflows.
  • Seamless Integration: Works effortlessly with modern JavaScript and TypeScript projects.

Conclusion

@clack/prompts is a powerful tool for creating interactive CLI applications with a focus on usability and developer experience. Its rich feature set, ease of use, and extensibility make it an excellent choice for developers aiming to craft intuitive and polished command-line interfaces.

Install it today and take your CLI tools to the next level!