Skip to content
2026 Edition · Complete Guide & Cheatsheet

Claude Code CLI

From zero to productive. Install, configure, save tokens, and write quality code — the complete guide for test automation engineers and developers who want to vibe code with AI.

Node.js 18+@anthropic-ai/claude-codeSonnet 4.6 defaultPlaywright · TypeScript
01Installation & First Launch

Node.js v18+ (use nvm to manage versions) and a paid Claude plan — Pro ($20/mo), Max 5x ($100/mo), Max 20x ($200/mo), or an API key.

Install & Launch
TERMINAL
# Install globally
$ npm install -g @anthropic-ai/claude-code

# Navigate to your project
$ cd ~/playwright-project

# Start Claude Code — browser opens for auth on first run
$ claude

# Or: use API key instead of subscription
$ export ANTHROPIC_API_KEY="sk-ant-..."
$ claude
💡
First thing to do after launch: Run /init to generate a starter CLAUDE.md. Then customize it with your project's stack, commands, and conventions.
02Pricing & Models
Plans
PlanPriceTokens / 5hr WindowBest For
Pro$20/mo~44KLearning, light usage
Max 5x$100/mo~88KDaily development
Max 20x$200/mo~220KHeavy professional use
APIPer tokenUnlimitedCI/CD, automation
Model Costs (API)
ModelInput / 1M tokOutput / 1M tokWhen to Use
Opus 4.6$5.00$25.00Complex architecture, hard debugging
Sonnet 4.6$3.00$15.00Daily coding — default, best balance
Haiku 4.5$1.00$5.00Quick lookups, simple edits, subagents
💡
Rule of thumb: Subscription users report 90%+ savings vs. API pricing. If your monthly API equivalent exceeds $100 → get Max 5x. Exceeds $200 → get Max 20x.
03CLI Commands & Flags
Launch Modes
TERMINAL
# Interactive session
$ claude

# One-shot: single prompt, get answer, exit
$ claude -p "explain the page object pattern in tests/pages/"

# Continue last conversation
$ claude --continue    # or -c

# Pick from recent sessions
$ claude --resume      # or -r

# Pipe input
$ cat test-results/errors.log | claude -p "explain these test failures"

# JSON output for scripting
$ claude -p "list all spec files" --output-format json

# Specify model
$ claude --model claude-sonnet-4-6
System Prompt Flags
FlagActionRecommendation
--append-system-prompt "text"Add to defaultsUSE THIS
--append-system-prompt-file pathAppend from fileUSE THIS
--system-prompt "text"Replace ALL defaultsCAREFUL
--system-prompt-file pathReplace from fileCAREFUL
TERMINAL
# Best practice: append rules for Playwright project
$ claude --append-system-prompt "Always use Page Object Model. Import test from src/fixtures/base.fixture.ts, not @playwright/test."

# CI/CD: run with rules from file
$ claude -p "review tests/" --append-system-prompt-file .claude/ci-rules.md
Permission & Safety
TERMINAL
# Allow specific tools
$ claude --allowedTools "Read,Grep,Glob,Write,Edit"

# YOLO mode — skip all prompts (containers only!)
$ claude --dangerously-skip-permissions
⚠️
--dangerously-skip-permissions should only be used inside containers or isolated CI environments. Never run with this flag in production systems.
04Slash Commands

Type these inside a running Claude Code session.

Essential (daily use)
CommandWhat It DoesExample / Tip
/clearWipe context — fresh startUse between unrelated tasks!
/compactSummarize & reduce tokens/compact focus on page objects
/modelSwitch AI model/model claude-haiku-4-5
/fastToggle Opus 4.6 at 2.5× speedFor quick iterations
/planExtended thinking modeFor complex refactors
/reviewCode review current changesBefore committing
/rewindUndo to any checkpointAlso: double-tap Esc
Session Management
CommandWhat It Does
/renameName session: /rename playwright-auth-refactor
/exportSave conversation to file
/todosList tracked TODO items
/add-dirAdd extra directories: /add-dir ~/api-project
/doctorHealth check installation
/permissionsManage allowed tools & commands
/output-styleChange response formatting
05Keyboard Shortcuts
ShortcutAction
EnterSend message
Shift + EnterNew line
Shift + TabCycle: Normal → Auto-accept → Plan mode
EscCancel current generation
Esc EscOpen rewind menu
Ctrl + CExit Claude Code
Ctrl + LClear screen (not context)
Recall previous message
ℹ️
Customize shortcuts: /keybindings → opens ~/.claude/keybindings.json. Changes apply instantly.
06Configuration Hierarchy

Claude Code uses a layered system. Higher specificity wins. Understanding this is key to making Claude write code the way you want.

FILE TREE
~/.claude/
    CLAUDE.md              ← Global: personal defaults for ALL projects
    settings.json          ← Global permissions, model preferences
    keybindings.json       ← Your keyboard shortcuts

./ (project root)
    CLAUDE.md              ← Project: team-shared (commit to git!)
    CLAUDE.local.md        ← Project: personal overrides (gitignored)
    .claudeignore          ← Files Claude should never read

./.claude/
    settings.json          ← Project settings (hooks, permissions)
    skills/
        SKILL.md           ← Project-wide skill
        playwright/
            SKILL.md       ← Domain-specific skill

./tests/
    CLAUDE.md              ← Directory-level: rules only for tests/
⚠️
Critical insight: Claude reads ALL applicable CLAUDE.md files on session start. Every token in these files counts against your context every single message. Keep them lean.
07CLAUDE.md — Project Context

This is the single most important file for code quality. It's your pair programmer's briefing. The golden rule: for each line, ask "Would removing this cause Claude to make mistakes?" If not, delete it.

Rules for an Effective CLAUDE.md
📏
Under 5K tokens

~3,500 words max. Every token is re-consumed every message. Bloated CLAUDE.md = wasted money.

🎯
Be specific, not verbose

"Use data-testid for selectors" beats a paragraph explaining why test-ids are preferred.

🔧
Include runnable commands

Build, test, lint commands prevent Claude from guessing and wasting tokens exploring.

🔄
Evolve it continuously

Found a new gotcha? Add it. Found a rule Claude already follows? Remove it.

Example: Playwright + TypeScript Project
CLAUDE.md
# Playwright E2E Test Framework

## Stack
Playwright 1.50+ · TypeScript 5.6+ · Faker.js · dotenv

## Commands
npm test              # run all tests
npm run test:ui       # Playwright UI mode
npm run test:chrome   # chromium only
npm run lint          # ESLint check
npm run typecheck     # TypeScript strict check

## Architecture
src/pages/       — Page Objects (extend BasePage)
src/fixtures/    — Custom Playwright fixtures (DI)
src/api/         — API client classes
src/utils/       — Env config, helpers, test data generator
src/data/        — Static test data, routes, users
tests/           — Test specs by feature

## Critical Rules
- ALWAYS import { test, expect } from `src/fixtures/base.fixture.ts`
  NOT from `@playwright/test`
- Use `data-testid` for selectors, never CSS classes
- Page objects: locators as readonly props, actions as methods
- Env vars via `src/utils/env.config.ts` — never hardcode
- Auth handled by `tests/auth.setup.ts` — tests start authenticated

## Naming
Files: kebab-case · Classes: PascalCase · Test IDs: kebab-case
Tests: start with "should" — "should login with valid credentials"

## Gotchas
- page.waitForTimeout() is an anti-pattern — use expect/waitForURL
- API tests don't use storageState — they get own token in beforeAll
- Never commit page.pause() — debug only
08Skills — Teach Claude Domain Knowledge

Skills are markdown instructions that Claude loads automatically when relevant. Unlike slash commands, Claude decides when to use them based on your request.

File Structure
FILE TREE
.claude/skills/
    SKILL.md                     ← Main project skill (auto-loaded)
    playwright-tests/
        SKILL.md                 ← Activated: "write a test", "fix spec"
    api-testing/
        SKILL.md                 ← Activated: "API test", "endpoint test"
    code-review/
        SKILL.md                 ← Activated: "review this", "check quality"
Skill Example: Playwright Test Writing
.claude/skills/playwright-tests/SKILL.md
---
name: playwright-tests
description: >
  Activated when writing, fixing, or modifying Playwright tests.
  Triggers: test, spec, e2e, playwright, page object, fixture.
---

# Playwright Test Guidelines

## Creating a New Test
1. Does it need auth? Import from the correct fixture:
   - Auth tests → `src/fixtures/auth.fixture.ts`
   - Regular tests → `src/fixtures/base.fixture.ts`
   - API only → `@playwright/test` directly

2. Create page object first if it doesn't exist:
   - Extend `BasePage` from `src/pages/base.page.ts`
   - Locators = readonly properties via `this.byTestId()`
   - Actions = methods, Assertions = `expectX()` methods

3. Register page object in `src/fixtures/base.fixture.ts`

## Locator Priority
1. getByTestId() ← most reliable
2. getByRole()   ← semantic
3. getByText()   ← visible text
4. getByLabel()  ← form fields
5. locator()     ← last resort

## Anti-Patterns
✗ page.waitForTimeout(ms) — use auto-waiting
✗ Hardcoded URLs — use ROUTES from data/routes
✗ Hardcoded creds — use USERS from data/users
✗ page.pause() in committed code
How Invocation Works
Auto-invocation
You: "Write a test for the checkout page"
→ Claude loads playwright-tests skill
→ Follows patterns from the skill
Explicit invocation
You: /playwright-tests login.spec.ts
→ Directly loads and applies skill
→ Useful for forcing specific behavior
09Hooks — Run on Every Event

Unlike prompts (which Claude may skip), hooks always execute. Use them for things that must happen every time — linting, type-checking, truncating output.

HookWhen It FiresExample Use
session-startNew session beginsLoad context, check dependencies
post-editAfter Claude edits a fileAuto-lint, auto-format
pre-commitBefore Claude commitsType-check, run affected tests
Setup for Playwright Project
.claude/settings.json
{
  "hooks": {
    "post-edit": [
      {
        "command": "npx eslint --fix $FILE 2>/dev/null || true",
        "description": "Auto-fix lint after every edit"
      }
    ],
    "pre-commit": [
      {
        "command": "npm run typecheck && npx playwright test --reporter=list 2>&1 | tail -20",
        "description": "Type-check + quick test before commit"
      }
    ]
  }
}
💡
Pro tip: truncate command output — Hook commands like | tail -20 or | head -50 prevent massive test logs from flooding your context window and eating tokens.
10Saving Tokens — 12 Commandments

Claude's context window fills up fast, and performance degrades as it fills. Managing tokens is the difference between hitting your limit in 1 hour vs. working all day.

1. /clear Between Unrelated Tasks
❌ Don't
Fix auth bug → write new page object → update config → all in one session → Context full of irrelevant history
✅ Do
Fix auth bug → /clear → write page object → /clear → update config → Each task gets clean context
2. /compact Proactively at 70%
# Don't wait for auto-compact at 95%. Do it manually at ~70%:
/compact focus on the auth setup refactoring decisions

# You can specify what to keep:
/compact keep only the page object patterns and fixture changes
3. Create a .claudeignore
.claudeignore
# Prevent Claude from reading these — saves thousands of tokens
node_modules/
dist/
build/
playwright-report/
test-results/
blob-report/
coverage/
*.lock
*.min.js
*.min.css
*.map
*.log
4. Use the Right Model for the Task
TaskModelCost
Design fixture architectureOpus 4.6
Write page objects & testsSonnet 4.6
Find a file, quick questionHaiku 4.50.2×
# Switch in-session:
/model claude-haiku-4-5     # for exploration
/model claude-sonnet-4-6    # back to normal work
5. Be Specific in Prompts
❌ Vague — wastes tokens exploring
"Fix the test failures in the auth tests"
✅ Specific — goes straight to the problem
"Fix the timeout in tests/auth/login.spec.ts line 34. Expected: redirect to /dashboard after login. Actual: waitForURL times out after 30s."
6. Give Direct File Paths
❌ Claude searches entire codebase
"Where is the login page object?"
✅ Zero search tokens
"Update src/pages/login.page.ts to add a forgotPassword locator"
7. Use Subagents for Exploration
# Subagent gets its own clean context — doesn't pollute yours
> Use a subagent to explore the src/api/ directory
  and report: what endpoints exist, error handling patterns,
  and whether we have retry logic.

# Claude spawns a focused agent, explores, reports back
# Your main context stays clean
8. Keep CLAUDE.md Under 5K Tokens

Every token is consumed every single session. A 2,000-token CLAUDE.md costs ~$0.006/session with Sonnet. At 100 sessions/day across 5 devs, that's $9/month just for reading CLAUDE.md. If it's 10K tokens → $45/month on context alone.

9. Truncate Command Output
❌ All output enters context
"Run all Playwright tests" → 200 tests × verbose output = huge token dump
✅ Targeted output
"Run tests in tests/auth/ with --reporter=line and show only failures" → Minimal, relevant output
10. Name Sessions with /rename
/rename playwright-auth-refactor
/rename adding-checkout-page-object

# Later, resume by name — no need to re-explain context:
$ claude --resume
11. Use --continue When Resuming
# Picks up exactly where you left off — zero re-explanation needed
$ claude --continue    # or: claude -c
12. Monitor Token Usage
# Bookmark your usage dashboard:
https://claude.ai/settings/usage

# In-session: status bar shows context %
# Rule: compact at 70%, /clear at task boundaries
ℹ️
The Three Biggest Token Wastes: 1) Redundant file reads (fix with .claudeignore + specific paths) → 2) Long sessions with mixed tasks (fix with /clear) → 3) Bloated CLAUDE.md (fix with ruthless pruning). Fix these three and you cut your bill in half.
11All Config Files for Quality Code

Here is every file you need to create in a new Playwright project to make Claude Code write production-quality code from day one.

Complete File Checklist
FILE TREE
playwright-project/
    CLAUDE.md                    ← Project brain (section above)
    CLAUDE.local.md              ← Your personal overrides (.gitignored)
    .claudeignore                ← Exclusions (section above)
    .claude/
        settings.json            ← Hooks + permissions (hooks section)
        skills/
            playwright-tests/
                SKILL.md         ← Test writing skill (skills section)
    .eslintrc.json               ← Linting rules Claude follows
    tsconfig.json                ← TypeScript strict mode config
    prettier.config.js           ← Formatting rules
    .editorconfig                ← Editor settings
    .env.example                 ← Template for environment vars
    .gitignore                   ← Include .env, auth/, reports/
    playwright.config.ts         ← Multi-project Playwright config
.claude/settings.json — Complete
.claude/settings.json
{
  "model": "claude-sonnet-4-6",
  "permissions": {
    "allow": [
      "Read", "Glob", "Grep", "Write", "Edit",
      "Bash(npm run *)",
      "Bash(npx *)",
      "Bash(git *)"
    ],
    "deny": [
      "Bash(rm -rf *)",
      "Bash(sudo *)"
    ]
  },
  "hooks": {
    "post-edit": [{
      "command": "npx eslint --fix $FILE 2>/dev/null || true",
      "description": "Auto-lint after every edit"
    }],
    "pre-commit": [{
      "command": "npm run typecheck && npm run lint",
      "description": "Quality gate before commit"
    }]
  }
}
The Quality Workflow
  1. 1
    Create config files

    Copy CLAUDE.md, .claudeignore, skills, settings.json, and .env.example from this guide. Commit everything except .env and CLAUDE.local.md.

  2. 2
    Launch Claude Code

    cd playwright-project && claude — Claude automatically reads CLAUDE.md, loads skills, applies hooks.

  3. 3
    Describe what you need

    "Create a page object for the checkout page with add-to-cart, remove-item, and proceed-to-payment actions. Then write tests for happy path and empty cart."

  4. 4
    Claude follows your patterns

    Because of your CLAUDE.md and skill file, Claude automatically uses BasePage, fixtures, test-ids, correct imports, and your naming conventions.

  5. 5
    Hooks auto-validate

    post-edit runs ESLint auto-fix. pre-commit runs type-check + lint. Quality is enforced without you asking.

12References & Official Docs

Always check official sources for the latest updates. This guide reflects the state as of March 2026.