Skip to main content

Shopify 開發的 Prompt 工程

一次令人沮喪的 Claude Code 工作階段和一次高效的工作階段之間的差異,往往取決於你如何撰寫 prompt。本指南提供經過實戰驗證的 prompt 範本和技巧,專門針對 Shopify 開發進行調校。

有效 Shopify Prompt 的原則

在深入範本之前,請先理解使 prompt 有效的四個原則:

  1. 明確 Shopify 情境:提及 API 版本、應用程式類型(Remix、自訂)、主題版本(OS 2.0)以及相關的 Shopify 概念
  2. 包含限制條件:像說明要做什麼一樣,也要說明不要做什麼——「使用 Polaris,不要使用自訂 UI 元件」
  3. 提供預期輸出的範例:當格式很重要時,展示一段你想要的內容片段
  4. 說明「為什麼」:當 Claude Code 理解商業邏輯時,能做出更好的決策
CLAUDE.md 的優勢

當你的 CLAUDE.md 檔案已經包含專案情境時,許多這些 prompt 可以更簡短。如果你的 CLAUDE.md 已指定「API version: 2025-01」和「UI: Polaris」,你就不需要在每個 prompt 中重複這些資訊。以下範本包含完整情境以供獨立使用——根據你的 CLAUDE.md 已涵蓋的內容進行精簡。

即用 Prompt 範本

App Extensions

1. 建立 Theme App Extension

Prompt: 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

Prompt: Checkout 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

Prompt: 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. 撰寫分頁查詢

Prompt: Paginated GraphQL Query
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

Prompt: GraphQL 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 查詢

Prompt: 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

Prompt: 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

Prompt: Mega Menu
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. 建立動態購物車抽屜

Prompt: Cart Drawer
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

Prompt: Discount Function (Rust)
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

Prompt: Delivery 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 處理程式

Prompt: Debug 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 處理程式

Prompt: Webhook with Retries
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. 產生完整的測試套件

Prompt: Test Suite
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 測試

Prompt: E2E Tests
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 介面

Prompt: 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

Prompt: App Bridge Migration
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 速率限制中介軟體

Prompt: Rate Limiting
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 流程

Prompt: Custom 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. 建立多地點庫存同步

Prompt: Inventory Sync
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 定義

Prompt: Metafield Setup
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 建立自訂店面

Prompt: Hydrogen Component
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 專案中真正發揮優勢的地方。

建置-測試-改進循環

Step 1: Build
> 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

漸進式增強

從簡單開始,逐層加入複雜度:

Progressive prompting
> 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

當你的任務跨越多個檔案時,請明確說明範圍:

Multi-file 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 開發最佳化。