Skip to main content

Shopify 开发的 CLAUDE.md 模板

CLAUDE.md 文件是有效使用 Claude Code 的基础。它提供 Claude Code 在每个会话开始时读取的持久上下文,消除了在每个提示中重复项目细节的需要。本指南提供了一个完整的、经过实战检验的 Shopify 开发项目模板。

为什么 CLAUDE.md 重要

没有 CLAUDE.md 文件,每个 Claude Code 会话都从零开始。Claude Code 必须发现你的项目结构、弄清楚你使用的 Shopify API 版本、学习你的编码约定并理解你的应用架构——全部通过读取文件和提问来完成。

有了一个编写良好的 CLAUDE.md,Claude Code 在每个会话开始时就像一个完全了解情况的团队成员:

  • 你的确切 Shopify 配置(API 版本、权限范围、应用类型)
  • 你的编码标准和架构决策
  • 如何运行、测试和部署项目
  • 应该避免哪些错误
5 分钟的投资

编写一个好的 CLAUDE.md 大约需要 5 分钟。它让你不必在每次会话中重复上下文,一周的开发下来轻松节省数小时的提示工程时间。这是你能为 Claude Code 工作流做的最高杠杆的事情。

完整模板

复制此模板,根据你的项目自定义方括号中的部分,并将其保存为项目根目录下的 CLAUDE.md

CLAUDE.md
# [Project Name]

## Overview
[One paragraph describing what this project does, who it's for, and its current status.]

Example: Remix-based Shopify app that enables merchants to create and manage
product bundles with automatic discount application. Currently in production
serving 200+ stores.

## Tech Stack
- **Framework**: Remix (Shopify app template)
- **Language**: TypeScript (strict mode)
- **Database**: Prisma ORM with PostgreSQL
- **UI**: Shopify Polaris v13 React components
- **Auth**: Shopify managed installation (app proxy + session tokens)
- **Testing**: Vitest (unit), Playwright (e2e)
- **Package Manager**: npm
- **Node Version**: 20 LTS

## Shopify Configuration
- **API Version**: 2025-01 (DO NOT use unstable or older versions)
- **App Type**: Embedded app (App Bridge 4)
- **Access Mode**: Online + Offline access tokens
- **Required Scopes**: read_products, write_products, read_orders, write_orders,
read_inventory, write_inventory, read_customers
- **Webhooks**: ORDERS_CREATE, PRODUCTS_UPDATE, APP_UNINSTALLED
- **Extensions**: Theme app extension (product-bundle-block), Checkout UI extension

## Project Structure

app/ routes/ # Remix routes (app..tsx = authenticated app pages) graphql/ # GraphQL query and mutation strings queries/ # Read operations mutations/ # Write operations models/ # Prisma model helpers (.server.ts) components/ # Shared React components (Polaris-based) utils/ # Utility functions webhooks/ # Webhook handlers jobs/ # Background job processors extensions/ product-bundle/ # Theme app extension checkout-upsell/ # Checkout UI extension prisma/ schema.prisma # Database schema migrations/ # Migration files tests/ unit/ # Vitest unit tests e2e/ # Playwright e2e tests fixtures/ # Test data and mocks


## Commands
```bash
# Development
npm run dev # Start Remix dev server
shopify app dev # Start with Shopify CLI (ngrok tunnel + auth)
npm run dev:extensions # Develop extensions locally

# Database
npx prisma db push # Apply schema changes (development)
npx prisma migrate dev # Create and apply migration
npx prisma studio # Open database GUI

# Testing
npm test # Run all Vitest tests
npm test -- --watch # Watch mode
npm run test:e2e # Run Playwright tests
npm run test:coverage # Generate coverage report

# Build & Deploy
npm run build # Production build
shopify app deploy # Deploy to Shopify
npm run lint # ESLint check
npm run typecheck # TypeScript type checking

Coding Standards

TypeScript

  • Strict mode enabled, no any types (use unknown and narrow)
  • Prefer interface over type for object shapes
  • All functions must have explicit return types
  • Use barrel exports (index.ts) for directories

React / Polaris

  • Use Polaris components exclusively for UI -- no custom CSS for standard patterns (buttons, forms, cards, modals, data tables)
  • Follow Polaris design patterns: Page > Layout > Card hierarchy
  • Use useAppBridge() for App Bridge interactions
  • Toast for success messages, Banner for persistent info/errors
  • Loading states: use Polaris SkeletonPage/SkeletonBodyText

GraphQL

  • All queries go in app/graphql/queries/ as exported template literals
  • All mutations go in app/graphql/mutations/
  • Always include userErrors { field message } in mutations
  • Use cursor-based pagination (never offset-based)
  • Prefix query names with operation: GetProducts, CreateBundle
  • Always specify the exact fields needed (no over-fetching)

Remix Patterns

  • Loaders return json() responses with typed data
  • Actions handle form submissions with proper validation
  • Use authenticate.admin(request) at the start of every loader/action
  • Redirect to /auth/login on authentication failures
  • Use defer() for non-critical data that can stream

Database

  • All database operations in *.server.ts files (never in components)
  • Use Prisma transactions for multi-table operations
  • Always include shopDomain in queries (multi-tenant isolation)
  • Soft delete with deletedAt timestamp (never hard delete)

Webhooks

  • Verify HMAC on all webhook endpoints
  • Respond within 1 second (offload heavy work to background jobs)
  • Implement idempotency using webhook ID tracking
  • Log webhook receipt with shop domain, topic, and webhook ID

错误处理

  • Never swallow errors silently -- always log with context
  • Use Remix CatchBoundary/ErrorBoundary for route-level errors
  • GraphQL errors: check userErrors array first, then network errors
  • External API calls: retry with exponential backoff (max 3 attempts)

Shopify-Specific Rules

API Usage

  • ALWAYS use API version 2025-01
  • Use the authenticated admin client from authenticate.admin(request)
  • Never hardcode shop domains or access tokens
  • Rate limiting: track GraphQL cost points, throttle at 80% capacity
  • Use bulk operations for large data sets (1000+ items)

Polaris Guidelines

  • Follow the Shopify App Design Guidelines for UX patterns
  • Use the AppProvider at the app root with i18n configuration
  • Navigation via Polaris NavMenu component
  • Forms use Polaris FormLayout with inline validation
  • Tables use IndexTable with bulk actions

App Bridge 4

  • Do NOT use createApp() (that's App Bridge 3)
  • Session tokens are available via the Remix authenticate helper
  • Navigation: use standard links, App Bridge handles framing
  • Resource pickers: use the app bridge resource picker API
  • Title bar: set via Remix route meta or ui.title-bar component

Theme Extensions

  • App blocks must be self-contained (own CSS/JS, no global pollution)
  • Use CSS custom properties for theme-aware colors
  • Liquid: always null-check objects before accessing properties
  • Schema settings must have sensible defaults
  • Test with multiple themes (Dawn, Refresh, and one vintage theme)

Testing Requirements

  • All new features must have unit tests
  • Critical paths (checkout, payments, inventory) need e2e tests
  • Minimum 80% code coverage on models and utils
  • Mock the Shopify admin client in tests (never call real API)
  • Test webhooks with sample payloads from tests/fixtures/webhooks/
  • Run npm test before committing (pre-commit hook enforces this)

Deployment Checklist

  1. All tests pass (npm test && npm run test:e2e)
  2. TypeScript compiles without errors (npm run typecheck)
  3. Lint passes (npm run lint)
  4. Database migrations are committed
  5. Environment variables are set in production
  6. Webhook URLs are registered for production domain
  7. Extensions are deployed (shopify app deploy)
  8. App review checklist completed (if submitting to app store)

Environment Variables

  • SHOPIFY_API_KEY - App API key (from Partner Dashboard)
  • SHOPIFY_API_SECRET - App secret key
  • DATABASE_URL - PostgreSQL connection string
  • REDIS_URL - Redis connection for background jobs
  • SENTRY_DSN - Error tracking (optional)

DO NOT commit .env files. Use .env.example as a template.

Known Issues

  • [List any active bugs, workarounds, or tech debt items]
  • Bulk operations occasionally timeout for shops with 50k+ products; current workaround is to chunk into batches of 10k
  • The checkout extension doesn't render in Safari < 16 due to a known Shopify bug (tracked in their issue tracker)

Architecture Decisions

  • We use offline access tokens for background jobs and online tokens for interactive sessions
  • Bundle pricing is calculated server-side and applied via Shopify Functions (not manual discount codes) for checkout integrity
  • Customer data is NOT stored locally; always fetch fresh from Shopify to maintain compliance with data protection requirements

## 模板变体

### 纯主题项目

如果你在开发 Shopify 主题(而非应用),请使用此简化版本:

```markdown title="CLAUDE.md for Theme Projects"
# [Theme Name]

## Overview
Custom Shopify theme based on Dawn 13.0 for [store name].
Online Store 2.0 compatible with full section-everywhere support.

## Tech Stack
- **Base Theme**: Dawn 13.0
- **Liquid**: Shopify Liquid (OS 2.0)
- **CSS**: Vanilla CSS with custom properties (no preprocessor)
- **JavaScript**: Vanilla ES6+ (no jQuery, no build step)
- **Icons**: Inline SVG from a central snippet

## Structure

assets/ # CSS, JS, and static files config/ # settings_schema.json and settings_data.json layout/ # theme.liquid and password.liquid locales/ # Translation files sections/ # All sections (reusable across templates) snippets/ # Reusable Liquid snippets templates/ # JSON templates (OS 2.0) customers/ # Account page templates


## Commands
```bash
shopify theme dev --store=mystore # Local development
shopify theme push # Push to theme
shopify theme pull # Pull remote changes
shopify theme check # Run Theme Check linter

Coding Standards

  • Sections must have complete schemas with sensible defaults
  • Always null-check Liquid objects: {% if product.metafields.custom.x %}
  • Use loading="lazy" on all images below the fold
  • CSS: mobile-first, use custom properties for colors/spacing
  • JavaScript: no global scope pollution, use IIFE or modules
  • Accessibility: all interactive elements must be keyboard navigable
  • Performance: no render-blocking JS, minimize Liquid loops

Shopify-Specific Rules

  • Use {{ image | image_url: width: 800 }} (not img_url filter)
  • Preload critical images with fetchpriority="high"
  • Use {% render 'snippet' %} (not include)
  • Section schema: always include "class" for wrapper styling
  • Test with Theme Check: shopify theme check --fail-level error

Known Issues

  • [List theme-specific bugs or browser compatibility notes]

### Hydrogen / 无头项目

```markdown title="CLAUDE.md for Hydrogen Projects"
# [Project Name] - Hydrogen Storefront

## Overview
Headless Shopify storefront built with Hydrogen 2024.10 and Remix.

## Tech Stack
- **Framework**: Hydrogen (Remix-based)
- **Language**: TypeScript
- **Styling**: Tailwind CSS
- **API**: Shopify Storefront API (2025-01)
- **Hosting**: Oxygen (Shopify's edge hosting)
- **Cache**: Hydrogen's built-in caching strategies

## Shopify Configuration
- **API Version**: 2025-01 (Storefront API)
- **Storefront Access Token**: In environment variables
- **Customer Account API**: Enabled for account features

## Key Patterns
- Use Hydrogen's `<Await>` for deferred data loading
- Cache strategies: CacheLong for collections, CacheShort for cart
- SEO: Use Hydrogen's `getSeoMeta()` helper for all routes
- Analytics: Use Hydrogen's built-in Shopify analytics
- Use `<Money>` and `<Image>` components from @shopify/hydrogen

Claude Code 如何使用 CLAUDE.md

了解 Claude Code 如何处理 CLAUDE.md 可以帮助你写出更好的文件:

  1. 会话开始时读取:Claude Code 在你的第一个提示之前读取 CLAUDE.md
  2. 始终在上下文中:内容在整个会话期间保留在上下文窗口中
  3. 层级合并:全局 (~/.claude/CLAUDE.md) + 项目根目录 + 子目录文件会被合并
  4. Token 成本:CLAUDE.md 消耗上下文 Token,因此要保持简洁。一个 500 词的 CLAUDE.md 大约是 700 个 Token——上下文窗口的一小部分
保持简洁

过长的 CLAUDE.md 会在每次交互中浪费上下文 Token。目标是 300-800 词。将详细文档放在单独的文件中——CLAUDE.md 应该是一个快速参考,而非一本小说。每个词都应该物有所值。

最佳实践检查清单

在编写或审查你的 CLAUDE.md 时使用此清单:

  • API version is specified (single most important line)
  • Tech stack is listed (framework, language, database, UI)
  • All dev commands are documented (dev, test, build, deploy)
  • File structure is outlined (key directories and their purposes)
  • Coding standards are explicit (not vague "write clean code")
  • Shopify-specific rules are stated (scopes, app type, extensions)
  • Testing expectations are clear (what to test, how to run tests)
  • Known issues are documented (prevents Claude Code from hitting the same walls)
  • Environment variables are listed (without actual values)
  • No sensitive data (no API keys, tokens, or passwords)
永远不要在 CLAUDE.md 中放置密钥

CLAUDE.md 是一个会提交到版本控制的普通文件。永远不要包含 API 密钥、访问令牌、数据库密码或任何敏感凭据。列出变量名称(例如 SHOPIFY_API_KEY),但不要列出它们的值。

演进你的 CLAUDE.md

你的 CLAUDE.md 应该随项目一起演进。在以下情况下更新它:

  • 升级 Shopify API 版本时
  • 添加新的扩展或 Webhook 时
  • 更改架构模式时
  • 发现新的会浪费时间的"陷阱"时
  • 添加或更改开发命令时
  • 团队编码标准演进时

过时的 CLAUDE.md 比没有 CLAUDE.md 更糟糕,因为它会给 Claude Code 自信但错误的上下文。保持它最新、简洁,并对项目的实际状态诚实。

下一步

有了 CLAUDE.md,你就可以开始探索 MCP 基础,了解 Model Context Protocol 如何进一步扩展 Claude Code 在 Shopify 开发中的功能。