Shopify 开发的 Prompt 工程
一次令人沮丧的 Claude Code 工作会话和一次高效的工作会话之间的差异,往往取决于你如何编写 prompt。本指南提供经过实战验证的 prompt 模板和技巧,专门针对 Shopify 开发进行调校。
有效 Shopify Prompt 的原则
在深入模板之前,请先理解使 prompt 有效的四个原则:
- 明确 Shopify 上下文:提及 API 版本、应用程序类型(Remix、自定义)、主题版本(OS 2.0)以及相关的 Shopify 概念
- 包含约束条件:像说明要做什么一样,也要说明不要做什么——"使用 Polaris,不要使用自定义 UI 组件"
- 提供预期输出的示例:当格式很重要时,展示一段你想要的内容片段
- 说明"为什么":当 Claude Code 理解业务逻辑时,能做出更好的决策
当你的 CLAUDE.md 文件已经包含项目上下文时,许多这些 prompt 可以更简短。如果你的 CLAUDE.md 已指定"API version: 2025-01"和"UI: Polaris",你就不需要在每个 prompt 中重复这些信息。以下模板包含完整上下文以供独立使用——根据你的 CLAUDE.md 已涵盖的内容进行精简。
即用 Prompt 模板
App Extensions
1. 构建 Theme App Extension
Build a Shopify theme app extension that displays product reviews
as a star rating and review list on product pages.
Requirements:
- App block with schema settings for: reviews per page (default 5),
show star rating (boolean), color scheme selector
- Liquid template that renders review data from metafields
- CSS that matches common Shopify theme styles
- JavaScript for "Load More" pagination
- Accessible: screen reader support for star ratings
Put the extension in extensions/product-reviews/.
Use the theme app extension file structure.
2. 构建 Checkout UI Extension
Build a Shopify checkout UI extension (checkout_ui) that shows
a free shipping progress bar.
Requirements:
- React component using @shopify/ui-extensions-react/checkout
- Show current cart total vs free shipping threshold ($75)
- Progress bar with percentage filled
- Dynamic messaging: "$X away from free shipping!" or "You qualify!"
- Use the Banner and ProgressBar checkout components
- Extension target: purchase.checkout.block.render
- Include shopify.extension.toml configuration
3. 构建 Admin Action Extension
Build a Shopify admin action extension that lets merchants bulk-tag
products based on inventory level.
Requirements:
- Admin action that appears on the Products index page
- React UI with Polaris components (Modal, TextField, Select)
- Options: tag name input, threshold selector (< 10, < 50, < 100)
- GraphQL mutation to add tags to matching products
- Loading states and success/error feedback
- Handle pagination for stores with 1000+ products
GraphQL 查询与 Mutation
4. 编写分页查询
Write a GraphQL query to fetch all orders from the last 30 days
with their line items, fulfillment status, and customer email.
Requirements:
- Cursor-based pagination with first: 50
- Filter by created_at >= 30 days ago using query parameter
- Include financial_status and fulfillment_status
- Include line items with product title, variant title, quantity, price
- Include customer email and order name
- Write the TypeScript types for the response shape
- API version 2025-01
5. 编写复杂的 Mutation
Write a GraphQL mutation to create a product with variants and
set metafields in a single API call.
Requirements:
- ProductCreate mutation with product title, description, vendor
- Include 3 variants with prices and inventory quantities
- Set a custom metafield (namespace: "custom", key: "material", type: "single_line_text_field")
- Include media (image URLs) attachment
- Handle userErrors in the response
- Write the TypeScript variables type
- Wrap it in a reusable async function that takes the admin client
6. 编写 Bulk Operation 查询
Write a Shopify bulk operation query to export all products with
their variant inventory levels across all locations.
Requirements:
- Use bulkOperationRunQuery mutation
- Include the JSONL polling logic to check completion
- Parse the JSONL response into structured data
- Handle the bulk operation lifecycle: CREATED -> RUNNING -> COMPLETED
- Include error handling for FAILED status
- Write this as a complete utility module I can import
Liquid 与主题开发
7. 创建 Liquid Section
Create a Liquid section called "collection-filter-grid" that displays
a filterable product grid.
Requirements:
- Collection picker in schema settings
- Filter by product type, vendor, and price range
- CSS Grid layout: 4 columns desktop, 2 tablet, 1 mobile
- Lazy-loaded product images with aspect ratio preservation
- Quick-add-to-cart button on hover
- Section schema with settings for: columns per row,
show vendor, show price, enable quick add
- Use section blocks for promotional cards between products
- No external JavaScript dependencies
8. 创建 Mega Menu Snippet
Create a Liquid snippet for a mega menu navigation that supports:
Requirements:
- 3 levels of navigation from linklists
- Desktop: full-width dropdown with columns
- Mobile: accordion-style expand/collapse
- Featured image area per top-level menu item (using metafields)
- Keyboard navigation (arrow keys, escape to close)
- ARIA roles and labels for accessibility
- Smooth CSS transitions (no jQuery)
- works with the "header" section's schema to configure menu handle
9. 构建动态购物车抽屉
Create a cart drawer (slide-out panel) using Liquid, CSS, and
vanilla JavaScript.
Requirements:
- Opens from right side on add-to-cart
- Real-time updates via Cart AJAX API (/cart.js, /cart/add.js)
- Line item quantity adjustment with +/- buttons
- Line item removal with undo option (3 second window)
- Free shipping progress bar
- Cart note textarea
- Upsell product recommendation (last item in a specific collection)
- Accessible: focus trap when open, escape to close
- CSS animations for open/close (transform, not left/right)
Shopify Functions
10. 生成 Rust 折扣 Function
Generate a Shopify Function in Rust that implements a "Buy X Get Y"
discount.
Requirements:
- Function API: product_discounts
- Input: cart lines, discount configuration from metafields
- Logic: if cart contains product X (by tag), apply percentage
discount to product Y (by tag)
- Handle edge cases: multiple qualifying items, quantity limits
- Include the shopify.extension.toml configuration
- Include run.graphql input query
- Write the Cargo.toml with correct Shopify Function dependencies
- Include unit tests for the discount logic
11. 生成 Delivery Customization Function
Generate a Shopify Function for delivery customization that hides
express shipping for orders containing oversized items.
Requirements:
- Function API: delivery_customization
- Check line items for a "oversized" tag
- If any oversized item exists, rename and reorder delivery options
to remove/hide express options
- Include input query, Rust implementation, and tests
- Handle the case where all items are oversized vs mixed carts
Webhook 处理程序
12. 调试 Webhook 处理程序
Debug this webhook handler for orders/create that's returning 500
errors intermittently:
[paste your webhook handler code here]
The error logs show: "Cannot read property 'id' of undefined"
on line 47. This happens on roughly 20% of webhook deliveries.
Check for:
- Payload structure differences between API versions
- Missing null checks on nested objects
- Race conditions with database writes
- Whether the 5-second timeout could be causing issues
13. 创建带有重试逻辑的 Webhook 处理程序
Create a webhook handler for PRODUCTS_UPDATE that syncs product
data to an external inventory system.
Requirements:
- HMAC verification using Shopify webhook secret
- Idempotency: track processed webhook IDs to skip duplicates
- Respond to Shopify within 1 second (use background job for heavy work)
- Retry external API calls with exponential backoff (3 attempts)
- Dead letter queue for permanently failed syncs
- Structured logging with webhook ID, product ID, and timing
- Use the Remix webhook handling pattern
测试
14. 生成完整的测试套件
Write a complete Vitest test suite for the product bundle
creation flow.
Files to test:
- app/routes/app.bundles.new.tsx (form submission)
- app/models/bundle.server.ts (database operations)
- app/graphql/mutations/bundleCreate.ts (GraphQL mutation)
Cover:
- Happy path: create bundle with 3 products
- Validation: empty title, too few products, duplicate products
- Auth: redirect when session expires
- Error: GraphQL errors, database constraint violations
- Edge: Unicode titles, maximum products (20), zero-price variants
Mock the Shopify admin GraphQL client and Prisma.
15. 生成 Playwright E2E 测试
Write Playwright end-to-end tests for our Shopify theme's
product page.
Test scenarios:
- Product page loads with correct title and price
- Variant selector changes price and image
- Add to cart with quantity > 1
- Cart drawer opens after add to cart
- Inventory limit prevents over-ordering
- Product with no variants shows simplified UI
- Mobile: variant selector works on touch devices
- Accessibility: page passes axe-core audit
Use Page Object pattern. Base URL: http://localhost:9292
代码生成与重构
16. 生成 Polaris CRUD 界面
Create a complete CRUD interface for managing shipping zones using
Shopify Polaris components.
Requirements:
- Index page with ResourceList showing all zones
- Filters: active/inactive, country
- Create/Edit form with: zone name, countries (multi-select),
rate conditions (price-based and weight-based)
- Delete confirmation modal
- Toast notifications for success/error
- Loading skeletons during data fetches
- Empty state with illustration
- Use Remix loader/action pattern for data flow
17. 重构至 App Bridge 4
Refactor our embedded app from App Bridge 3 to App Bridge 4.
Current code uses:
- createApp() initialization
- getSessionToken() for auth
- Redirect.create() for navigation
- ResourcePicker.create() for product selection
Migrate to App Bridge 4 patterns:
- Direct token access from shopify.idToken()
- URL-based navigation via app bridge
- New resource picker API
- Update all import paths
- Remove the app bridge provider wrapper if using Remix template
18. 生成 API 速率限制中间件
Create rate limiting middleware for our Shopify app's API calls.
Requirements:
- Track Shopify's GraphQL cost points (2000 point bucket)
- Parse X-Shopify-Shop-Api-Call-Limit headers for REST
- Implement leaky bucket algorithm for request throttling
- Queue system for bulk operations
- Per-shop rate tracking (multi-tenant)
- Logging when approaching limits (> 80% consumed)
- Automatic retry with backoff when rate limited
- TypeScript, works with our Remix app structure
19. 生成 Shopify App OAuth 流程
Implement a complete Shopify OAuth flow for a custom (non-Remix
template) Node.js app.
Requirements:
- Install endpoint: generate auth URL with required scopes
- Callback endpoint: exchange code for access token
- HMAC validation on the callback
- Store tokens securely (encrypted at rest in PostgreSQL)
- Handle token refresh for online access mode
- Verify installed shops on subsequent requests
- Handle app uninstall webhook to clean up data
- Include CSRF protection with state parameter
20. 创建多地点库存同步
Build an inventory synchronization system that keeps Shopify
inventory in sync with an external warehouse API.
Requirements:
- Scheduled job (runs every 15 minutes)
- Fetch inventory levels from external API (REST, paginated)
- Compare with Shopify inventory via GraphQL bulk query
- Calculate deltas and apply adjustments
- Use inventoryAdjustQuantities mutation (not deprecated individual)
- Handle multiple locations (map external warehouse IDs to Shopify location IDs)
- Conflict resolution: external system is source of truth
- Detailed sync log with item-level results
- Alert on sync failures via webhook to Slack
额外 Prompt
21. 生成 Metafield 定义
Create a migration script that sets up all required metafield
definitions for our product customization app.
Metafields needed:
- products: custom.material (single_line_text_field)
- products: custom.care_instructions (multi_line_text_field)
- products: custom.size_chart (json, with validation)
- variants: custom.weight_grams (number_integer)
- orders: custom.gift_message (single_line_text_field)
Use the metafieldDefinitionCreate mutation. Make it idempotent
(skip if definition already exists). Include validation rules.
22. 使用 Hydrogen 构建自定义店面
Create a Hydrogen (Remix + Storefront API) product page component
that includes:
- Product image gallery with zoom
- Variant selector with option swatches
- Price display with compare-at-price
- Dynamic add-to-cart with cart optimization
- SEO meta tags and structured data (JSON-LD)
- Streaming with Suspense boundaries for deferred data
- Use Hydrogen's built-in components where available
迭代 Prompt 技巧
单一 prompt 很强大,但迭代 prompt 才是 Claude Code 在复杂 Shopify 项目中真正发挥优势的地方。
构建-测试-改进循环
> Create a webhook handler for ORDERS_CREATE that calculates
loyalty points and stores them in customer metafields.
# Claude Code writes the initial implementation
> Step 2: Test
> Write tests for this handler covering the edge cases we discussed.
# Claude Code writes tests, some may fail
> Step 3: Refine
> The test for zero-dollar orders is failing. The handler should
award 0 points but still update the metafield. Fix the handler.
# Claude Code fixes the specific issue
渐进式增强
从简单开始,逐层加入复杂度:
> Create a basic product recommendation section that shows
4 related products from the same collection.
# Get the basics working first
> Now enhance it: add a "You might also like" heading, lazy-load
the images, and add quick-add-to-cart buttons.
# Layer on features
> Now make it personalized: use the customer's order history
(via Storefront API) to weight recommendations. Fall back to
collection-based if no history exists.
# Add sophisticated logic
一个要求所有功能的庞大 prompt 往往会产生在出错时更难调试的代码。迭代构建意味着在加入下一层之前,每一层都已经正常工作。这也让 Claude Code 的响应保持专注且易于管理。
多文件项目 Prompt
当你的任务跨越多个文件时,请明确说明范围:
> This change needs to touch multiple files:
1. Add a new GraphQL query in app/graphql/queries/loyaltyPoints.ts
2. Create a new route at app/routes/app.loyalty.tsx
3. Add a Prisma model for LoyaltyTransaction in prisma/schema.prisma
4. Create a background job in app/jobs/calculatePoints.server.ts
5. Add the webhook handler in app/webhooks/orders-create.ts
6. Write tests for the calculation logic
Start with the Prisma model, then the GraphQL query, then build
up from there. Run prisma db push after creating the model.
会话管理命令
/compact——回收上下文
当你已经工作一段时间且上下文变得很大时,使用 /compact:
> /compact
# Summarizes the conversation, freeing up context space
# Your CLAUDE.md context is preserved
# Continue working on the same task with full project awareness
何时使用:完成一个功能后,在同一会话中开始下一个功能之前。
/clear——全新开始
当切换到完全不同的任务时,使用 /clear:
> /clear
# Wipes all conversation context
# CLAUDE.md is re-read on next prompt
# Perfect for switching from theme work to app work
何时使用:在不相关的任务之间切换时(例如,从主题开发切换到应用程序后端工作)。
/cost——监控费用
> /cost
# Shows tokens consumed and estimated cost
# Use this periodically during long sessions
何时使用:在活跃开发期间每 30-60 分钟使用一次,或在开始大型任务之前使用。
如果 Claude Code 的响应开始失去连贯性或"忘记"先前的决策,你可能已经填满了上下文窗口。请立即使用 /compact。如果这没有帮助,使用 /clear 并以一个专注的 prompt 和良好的 CLAUDE.md 上下文重新开始。
应避免的反模式
| 反模式 | 为什么会失败 | 更好的方法 |
|---|---|---|
| "构建我的整个应用程序" | 太模糊、太大 | 分解为功能级别的 prompt |
| "让它更好" | 没有具体方向 | "通过添加分页来改善性能" |
| "修复这个 bug"(无上下文) | Claude Code 需要错误细节 | 粘贴错误消息和相关代码 |
| 每个 prompt 都重复上下文 | 浪费 token | 将稳定的上下文放在 CLAUDE.md 中 |
| 从不使用 /compact | 上下文溢出 | 每完成一个功能就压缩 |
下一步
有了这些 prompt 模板,请继续前往 CLAUDE.md 模板,获取一个完整的、可直接复制粘贴的项目配置文件,专为 Shopify 开发优化。