Building an E-Commerce Frontend with AI-Assisted Development: Practices and Evaluation from Zero to One
Generative coding tools can quickly scaffold page structures, routes, basic styles, and simple interactions, making them useful for prototyping and small-to-mid-sized frontend projects. This article walks through the practical process of using AI assistance to build a ten-page e-commerce frontend from scratch, covering consistency requirements across data, routing, visual design, and interaction states; requirement breakdown and prompt design; project structure and mock data decoupling; form validation; responsive layout; and a final acceptance checklist for evaluating AI-generated projects.
Building an E-Commerce Frontend with AI-Assisted Development: Practices and Evaluation from Zero to One
Background: Opportunities and Limits of AI-Generated Projects
Generative coding tools can build page skeletons, routes, base styles, and simple interactions in a short time, which makes them suitable for prototype validation and small-to-mid-sized frontend projects. However, when generating a complete site from zero to one, the difficulty lies not in individual pages but in overall consistency. Data structures, navigation relationships, visual specifications, and state handling must be unified across pages—otherwise the site ends up looking like “every page was written by a different person.”
In real-world evaluations, common problems fall into the following categories:
- Incomplete coverage: The page count looks right, but the purchase flow is broken, and some pages contain only a title and empty space.
- Visual issues: Incomplete mobile adaptation, broken layouts on login and registration pages, button text with insufficient contrast against the background, and images that are all placeholders.
- Engineering issues: Chaotic directory structures with duplicate folder names; missing dependencies or configuration that prevent the project from starting; mock data written directly into components, which creates large refactoring efforts when real APIs are connected later.
- Code quality issues: Styles and logic are separated, but directories like
hooksandcontextcontain only empty files—the structure looks complete but carries no actual responsibilities.
Therefore, when evaluating the value of AI-assisted tools, focus on whether they can maintain consistency across the overall structure, not just on how fast the first generation is.
Scope: Feature List for Ten Pages
Before starting, list out the pages and core data clearly. This forms the basis for subsequent prompts and acceptance criteria. The table below outlines a typical e-commerce frontend’s page scope.
| Page | Core Features | Key Data |
|---|---|---|
| Home (Product List) | Category filtering, keyword search, sorting, pagination | Product list |
| Product Detail | Image browsing, variant selection, stock indicator | Product detail |
| Purchase | Shipping information, quantity adjustment, amount calculation | Cart items, shipping address |
| Purchase Success | Order number display, links to view orders or continue shopping | Order summary |
| Login | Credential validation, error messages, login state persistence | User credentials |
| Registration | Field validation, agreement checkbox, duplicate account detection | User information |
| User Center Overview | Account info, order overview, pending reminders | Aggregated data |
| Orders | Filtering by status, order detail view | Order list |
| Wallet (Coupons) | Balance display, coupon list, expiration reminders | Coupon list |
| Settings | Profile editing, password change, notification preferences | User configuration |
Once the page list is defined, clarify four things for each page: which data it reads, which data it submits, which states it has (loading, empty, error, success), and which pages it navigates to. These four points reduce ambiguity during generation.
Four Dimensions of Consistency
Overall site consistency can be broken down into four verifiable dimensions.
1. Consistent Data Structures
The same entity should use a single field definition across all pages. When a product appears in the list, detail, cart, and order pages, the field names and types must not differ. Define data models centrally in the project:
/*** Product data model, shared by all pages* @typedef {Object} Product* @property {string} id* @property {string} name* @property {number} price Unit: yuan, two decimal places* @property {number} stock Stock quantity, non-negative integer* @property {string[]} images Image URL list, at least one*/
Handle monetary amounts using the smallest unit or fixed decimal places to avoid floating-point calculation errors. Order amounts submitted should be based on the server’s result; frontend calculations are for display only.
2. Consistent Routing and Navigation
Ten pages require a complete route table, and every entry point must reach its corresponding page. The user center sub-pages should share a single layout component, with sidebar navigation highlighting driven by the current route. When the login session expires, users should be redirected uniformly to the login page and returned to the original page after logging in.
3. Consistent Visual Specifications
Colors, font sizes, spacing, and border radii should be managed through unified variables rather than hardcoded values in each component.
:root {--color-primary: #1677ff;--color-text: #1f2329;--color-on-primary: #ffffff;--color-danger: #d4380d;--spacing-base: 8px;--radius-base: 4px;}.button-primary {background: var(--color-primary);color: var(--color-on-primary);padding: var(--spacing-base) calc(var(--spacing-base) * 2);border-radius: var(--radius-base);}
Color combinations must be checked for contrast. Body text should have a contrast ratio of at least 4.5:1, and large text at least 3:1. Problems like “white text on a white background” appear easily during generation; a single pass with a contrast checking tool prevents an entire site of invisible buttons.
4. Consistent Interaction States
Similar operations should produce identical feedback across pages. For example, all list pages should have three states—loading, empty data, and request failure—and all form submissions should disable the button and show progress. Inconsistent states are a major source of the “rough” feeling users perceive.
Requirement Breakdown and Prompt Design
Generating the entire site in one shot is fast but carries the highest consistency risk. A more reliable approach is phased execution:
- Set up the data models, route table, and shared style variables.
- Implement shared components, such as the top navigation, product card, form inputs, and state placeholder components.
- Generate pages one by one, checking each against the acceptance checklist immediately after completion.
- Integrate navigation and data flow between pages.
- Check mobile adaptation and visual details.
Prompts for each step should include explicit constraints. A reusable template looks like this:
Goal: Generate the "Product Detail" page.Data: Use the defined Product model; see the fields in models/product.States: Include loading, empty data, and request failure states.Interactions: Switching variants updates price and stock indicator; disable the "Buy" button when stock is 0.Constraints:- Use only variables defined in the styles directory; do not add new color values.- Share the top navigation and footer components with other pages.- Layout must work correctly at 375px mobile width with no horizontal scrolling.- Import mock data from the mocks directory; do not write it inside components.Acceptance: List the page's route, the data fields it depends on, and its navigation relationships.
The more specific the constraints in a prompt, the closer the output matches expectations. Asking the tool to list routes, dependent fields, and navigation relationships after completion also makes manual review faster.
Project Structure and Mock Data Decoupling
The project structure should be settled early, with a clear responsibility for every directory.
src/api/ API wrappers; can return mock data at this stagemocks/ Mock data, separated from business componentscomponents/ Shared componentspages/ Page components, one directory per pagehooks/ Reusable logic, such as data loading and form statecontext/ Global state, such as login info and cartstyles/ Global styles and design variablesutils/ General utility functions
Once mock data is decoupled from business code, connecting real APIs only requires replacing the API layer—page components stay untouched. Here is a simple example:
// api/productApi.jsimport { mockProducts } from '../mocks/products.js';const config = {useMock: true,baseUrl: '/api',};export async function fetchProducts(query = {}) {if (config.useMock) {const keyword = query.keyword ?? '';return mockProducts.filter((item) => item.name.includes(keyword));}const params = new URLSearchParams(query).toString();const res = await fetch(`${config.baseUrl}/products?${params}`);if (!res.ok) {throw new Error(`Product request failed with status: ${res.status}`);}return res.json();}
Page components only call fetchProducts and don’t care whether data comes from mocks or a real service. The toggle is controlled by configuration, making gradual replacement straightforward during integration.
Empty directories also need handling. If directories like hooks or context contain only empty files, either fill them with code that has real responsibilities or delete them. Empty placeholders mislead future maintainers into thinking certain logic already exists.
Form Validation
The login, registration, purchase, and settings pages all contain forms. Validation rules should be managed centrally to avoid duplication across pages.
Validation falls into two categories:
- Synchronous validation: Format checks, such as phone number length, password length, and whether two password entries match.
- Asynchronous validation: Server-dependent checks, such as whether an account is already registered. Asynchronous validation should be debounced and must not replace server-side validation at submission time.
// utils/validate.jsconst rules = {phone: (value) => /^1[3-9]\d{9}$/.test(value) || 'Please enter an 11-digit phone number',password: (value) => value.length >= 8 || 'Password must be at least 8 characters',confirmPassword: (value, values) =>value === values.password || 'The two passwords do not match',};export function validate(values) {const errors = {};for (const field of Object.keys(rules)) {const result = rules[field](values[field] ?? '', values);if (result !== true) {errors[field] = result;}}return errors;}
In practice, run a full validation before submission; if there are errors, block the submission and show messages next to the corresponding fields. Error messages should appear near the input fields, not as a single vague message at the top of the page. The registration page’s “agreement checkbox” should follow the same rule set—submission is blocked until it is checked.
Responsive Layout and Image Assets
1. Responsive Layout
A mobile-first approach means designing a single-column layout for small screens first, then expanding to multiple columns on larger screens. Common breakpoints can be set around 768px and 1024px. Form pages like login and registration should have a maximum width and be centered on wide screens, preventing input fields from stretching too long.
Verify at least two widths: 375px (common phone width) and 1280px (common desktop width). Checks should include text truncation, button clickability, and image distortion.
2. Image Assets
Placeholder images are only for the development stage, but they should preserve correct dimensions and aspect ratios to avoid layout shifts during later replacement. Recommended practices:
- Preset aspect ratios for image containers so the layout stays stable before and after loading.
- Use lazy loading on list pages to reduce initial requests.
- Provide meaningful alt text for every image, supporting accessibility and failure states.
- Host image files on object storage and generate thumbnails of different sizes through an image processing service, avoiding direct loading of original images on the frontend.
Acceptance Checklist
A page or the whole site is complete only after passing the following checks:
- All ten pages are directly accessible via their routes, with no 404s.
- The purchase flow is complete: product detail, purchase, and purchase success, with data passing correctly between pages.
- Navigation among login, registration, and the user center is consistent with login state.
- All forms have field-level validation, with clear messages for empty submissions and invalid input.
- List and detail pages implement loading, empty, and error states.
- Layout works correctly at 375px and 1280px widths, with no horizontal scrolling.
- Text-to-background contrast meets requirements, and button text is clearly visible.
- Dependencies install and the project builds successfully.
Conclusion
AI-assisted development dramatically shortens the time from zero to a working prototype, but the real challenge of a complete site lies in consistency. By defining page scope upfront, enforcing unified data structures, routing, visual variables, and interaction states, designing constraints-rich prompts for each generation phase, decoupling mock data from business code, and validating against a concrete checklist, AI-assisted development can produce results that are not just fast but genuinely production-ready in structure.
