Getting Started
Quick start guide to install and use format-prompt in your JavaScript or TypeScript project
Installation
Install format-prompt using your preferred package manager:
# npm
npm install format-prompt
# bun
bun add format-prompt
# pnpm
pnpm add format-prompt
# yarn
yarn add format-promptBasic Usage
Importing
import { prompt } from 'format-prompt';Simple Example
import { prompt } from 'format-prompt';
const result = prompt`
Hello world!
This is a formatted prompt.
`;
console.log(result);
// Output: "Hello world!\nThis is a formatted prompt."With Variables
const name = 'John';
const age = 30;
const result = prompt`
User Information:
Name: ${name}
Age: ${age}
`;
console.log(result);
// Clean output without extra whitespaceComplex Example
import { prompt } from 'format-prompt';
function createAnalysisPrompt(email: string) {
return prompt`
You are a security guard that analyzes emails for:
* Spam: unsolicited bulk/promotional content
* Scam: phishing, fraud, identity theft attempts
* Toxicity: hate speech, threats, harassment
* Business relevance: legitimate business inquiries
Email to analyze:
${email}
Provide a detailed security assessment.
`;
}
const analysis = createAnalysisPrompt('test@example.com');How It Works
The prompt function:
- Takes a template literal string with optional interpolated values
- Removes leading/trailing whitespace from each line
- Collapses multiple spaces into single spaces
- Preserves intentional line breaks
- Trims the final result
- Returns a clean, token-efficient string
TypeScript Support
format-prompt is written in TypeScript and includes type definitions:
import { prompt } from 'format-prompt';
// Full type safety
const result: string = prompt`Your prompt here`;Best Practices
- Use template literals: Leverage JavaScript's template literal syntax for clean code
- Indent for readability: Format your prompts for readability in code - the library will clean it up
- Use interpolation: Insert variables directly into your prompts
- Keep structure: The library preserves intentional line breaks and structure
Common Patterns
List Formatting
const items = ['item1', 'item2', 'item3'];
const result = prompt`
Please analyze:
* ${items[0]}
* ${items[1]}
* ${items[2]}
`;Multi-line Instructions
const result = prompt`
Step 1: Read the input
Step 2: Process the data
Step 3: Generate output
Be thorough and accurate.
`;Dynamic Content
function generatePrompt(context: string, question: string) {
return prompt`
Context: ${context}
Question: ${question}
Provide a detailed answer based on the context.
`;
}