Engineering Practice: AI-Assisted E-commerce Frontend Development from 0 to 1
This article explores the engineering practices of using AI to assist in building an e-commerce frontend from scratch. It covers task decomposition, engineering structure layering, and key implementation details such as mock data decoupling, form validation, responsive layout, and state management. Additionally, it offers an evaluation framework for AI-generated code and a comprehensive quality checklist to ensure delivery readiness.
1. Background: AI-Assisted Programming Enters the Engineering Implementation Phase
Intelligent programming tools can now generate pages, components, and business logic based on natural language descriptions. Consequently, the problems developers face have shifted. The past focus was on “whether code can be written,” whereas now it is more about “whether the generated code can run, be modified, and be delivered.”
Building a complete e-commerce site from scratch is a typical scenario to test this capability. It covers common frontend challenges like routing, forms, state management, data display, permission division, and responsive layout. A single project can expose the shortcomings of AI-generated code in terms of structure, robustness, and detail.
This article does not evaluate specific tools but abstracts a general methodology: how to decompose tasks, design engineering structures, supplement key capabilities based on AI-generated code, and determine whether a generation result is qualified.
2. Task Decomposition: Defining Page Scope and Dependencies
Before submitting generation tasks, break down the requirements into verifiable page units. A typical e-commerce frontend can be divided into four groups:
- Public Browsing Group: Homepage (product list), product detail page.
- Transaction Group: Checkout page (confirm order and enter information), purchase success page.
- Account Group: Login page, registration page.
- User Center Group: Overview dashboard, order list, wallet and coupons, account settings.
When splitting, mark the dependencies between pages. For example, the checkout page depends on the login state and product detail data; all sub-pages in the user center depend on the login state. Once dependencies are clear, you can determine the generation sequence: complete the account and routing skeleton first, then the product data flow, and finally the transaction chain.
Each page needs to specify three types of acceptance criteria:
- Functional Criteria: The result after clicking, inputting, and navigating.
- Exception Criteria: How to prompt when the form is empty, the API fails, or the product is out of stock.
- Visual Criteria: Layout requirements at mobile and desktop widths, as well as primary colors and button contrast.
The more specific the acceptance criteria, the easier the subsequent checks, and the easier it is to spot deviations in AI-generated code.
3. Engineering Structure: Layering is More Important than a Single File
Early generated projects often write pages, styles, mock data, and business logic in the same file. This structure can run during demos, but modifying one part easily affects others. It is recommended to layer by responsibility:
src/pages/ Page-level components, responsible only for composition and routingcomponents/ Reusable UI components, such as product cards, form inputsservices/ Data access layer, encapsulating API callsmock/ Mock data, separated from business codeutils/ Pure functions for validation, formatting, state checkingstyles/ Global variables, base styles, and responsive rules
The core principle of layering is a unidirectional dependency: pages depend on components and services, while services do not depend on pages. This way, when replacing data sources, you only need to modify the service layer without changing the page code.
4. Key Implementation Points
4.1 Decoupling Mock Data from Business Code
An obvious issue in original projects is that mock data is written directly inside components. The correct approach is to place data into an independent module and provide an interface through a unified service function.
// mock/products.jsexport const products = [{ id: 'p-001', name: 'Sample Product A', price: 99.0, stock: 20, image: '/placeholder/p-001.png' },{ id: 'p-002', name: 'Sample Product B', price: 199.0, stock: 0, image: '/placeholder/p-002.png' },];// services/productService.jsimport { products } from '../mock/products';// Currently returns mock data. Replace the implementation later as needed.export async function fetchProducts() {return products;}export async function fetchProductById(id) {const item = products.find((p) => p.id === id);if (!item) {throw new Error('Product not found');}return item;}
This yields three benefits. First, page components are unaware of the data source, so no interface code needs modification when integrating real APIs. Second, exception branches (like product not found) can be defined uniformly in the service layer, avoiding repetitive checks on every page. Third, mock data can be expanded for test scenarios, such as adding edge cases like “out of stock” or “price is zero.”
4.2 Rule-Based Implementation of Form Validation
Registration, login, and checkout pages all require form validation. Writing validation rules as data is easier to maintain than writing conditional logic in every input field.
// utils/validate.jsconst rules = {username: [{ test: (v) => v.trim().length > 0, message: 'Username cannot be empty' },{ test: (v) => /^[a-zA-Z0-9_]{4,16}$/.test(v), message: 'Username must be 4-16 characters of letters, numbers, or underscores' },],phone: [{ test: (v) => /^\d{10}$/.test(v), message: 'Please enter a valid phone number' },],password: [{ test: (v) => v.length >= 8, message: 'Password must be at least 8 characters' },{ test: (v) => /[A-Za-z]/.test(v) && /\d/.test(v), message: 'Password must contain both letters and numbers' },],};export function validateForm(values) {const errors = {};for (const field of Object.keys(rules)) {const value = values[field] ?? '';const failed = rules[field].find((rule) => !rule.test(value));if (failed) {errors[field] = failed.message;}}return errors;}
When using it, call validateForm before submission. If the returned object is not empty, prevent submission and display error messages below the corresponding fields. Validation rules are defined in one place, allowing the registration and login pages to reuse the same set of functions.
Two points to note: First, frontend validation only improves the experience and cannot replace backend validation, as requests can bypass the UI. Second, password rules should be consistent with the backend; otherwise, users might pass frontend checks but be rejected upon submission, resulting in a worse experience.
4.3 Responsive Layout and Login Form Deformation
Common issues with mobile adaptation fall into two categories: fixed container widths causing overflow, and forms stretching or deforming between large and small screens. The recommended approach is to use fluid widths with maximum width limits and adjust grid columns via media queries.
/* styles/layout.css */.container {width: 100%;max-width: 1200px;margin: 0 auto;padding: 0 16px;box-sizing: border-box;}.product-grid {display: grid;grid-template-columns: repeat(2, 1fr);gap: 12px;}@media (min-width: 768px) {.product-grid {grid-template-columns: repeat(4, 1fr);gap: 20px;}}/* Login and registration forms use max-width to prevent stretching on wide screens */.auth-form {width: min(100%, 360px);margin: 0 auto;}.auth-form input {width: 100%;box-sizing: border-box;}
Deformation in login/registration pages is mostly caused by fixed input widths without setting box-sizing, where padding pushes the element beyond the container. Uniformly setting box-sizing: border-box resolves most of these cases.
4.4 Colors and Contrast
The issue of “white text on a white background” on buttons is essentially insufficient contrast between foreground and background colors. The primary color can follow the brand color, but text and background should meet readability requirements. A common benchmark is: contrast ratio between normal body text and background should be no less than 4.5:1, and for large text, no less than 3:1.
In practice, colors can be defined as variables for centralized management:
:root {--color-primary: #0052d9;--color-primary-text: #ffffff;--color-danger: #d54941;--color-text: #1d2129;--color-bg: #f5f7fa;}.btn-primary {background: var(--color-primary);color: var(--color-primary-text);}
With centralized color management, modifying the theme requires changing only one place, and it is easier to check which combinations fail contrast requirements.
4.5 State Control for the Shopping Flow
Order state is the most error-prone part of an e-commerce system. Writing allowed state transitions as explicit rules prevents illegal operations, such as shipping an unpaid order directly.
// utils/orderState.jsconst transitions = {created: ['paid', 'cancelled'],paid: ['shipped', 'refunding'],shipped: ['completed'],refunding: ['refunded'],};export function canTransition(from, to) {return (transitions[from] || []).includes(to);}export function assertTransition(from, to) {if (!canTransition(from, to)) {throw new Error(`Invalid order state transition: ${from} -> ${to}`);}}
When submitting an order on the checkout page or canceling an order in the user center, assertTransition should be called first. This way, state rules exist in a single file, and tests only need to cover this one module.
The purchase success page should only be displayed after the order status is confirmed as “created” or “paid.” If a user directly accesses the page URL, they should be redirected to the user center to avoid displaying non-existent order information.
5. AI-Assisted Development Workflow
When AI generates code, the task granularity directly affects the result quality. There are two common workflows.
One-shot Generation: Hand the complete requirements to the tool, expecting a runnable project in one output. The advantage is speed, suitable for building skeletons. The disadvantage is that errors are concentrated, troubleshooting is difficult, and common errors often require multiple rounds of fixes to run properly.
Staged Iteration: Generate the skeleton first, then supplement functions page by page, running verification at each step. The advantage is that errors are localized, and the scope of each change is small. The disadvantage is the need for manual phase planning and continuous checking.
In practice, the two methods can be combined: use one-shot generation for the skeleton and common components, and advance business pages and exception handling in stages. After completing each phase, three things must be done: start the project, walk through the core flow, and check the console for errors.
Whether AI-generated results are usable can be evaluated from the following dimensions:
- Runnability: Can the project install dependencies and start normally without console errors on first run.
- Flow Completeness: Can every step from browsing to placing an order to viewing the order be completed.
- Exception Handling: Are there clear prompts for empty data, API failures, and form errors.
- Structural Rationality: Is it layered, and is mock data separated from business code.
- Visual Consistency: Is the primary color unified, is there mobile overflow, and is button text clearly visible.
- Resource Completeness: Are images real resources or replaceable placeholders, and do placeholders have uniform naming and sizing.
6. Quality Check Checklist
Confirm item by item before delivery:
- The project installs dependencies and starts from scratch with no console errors.
- Registration, login, logout, and protected page redirection logic are correct.
- Every form behaves correctly under three conditions: empty values, incorrect format, and correct input.
- Product details display clearly when out of stock or when the product does not exist.
- On narrow and wide screens, lists, forms, and navigation have no horizontal scrollbars.
- All button text and backgrounds meet contrast requirements.
- Mock data is centralized in one directory; replacing it with APIs requires no changes to page components.
- Order state transitions pass through a unified validation function.
7. Summary
The difficulty of building an e-commerce frontend lies not in a single page, but in the dependencies between pages, the source of data, exception handling, and visual consistency. AI-assisted development can significantly shorten the time to build a skeleton, but the code it generates still requires engineering judgment.
The practical recommendations can be summarized in three points. First, define the page scope and acceptance criteria before submitting generation tasks. Second, use layered structures and rule-based validation and state management to replace scattered logic. Third, incorporate running, walkthroughs, and contrast checks into each iteration rather than leaving them for a final fix.
Following this methodology, teams can obtain a clearly structured, evolvable frontend project within a short cycle, focusing manual effort on business rules and experience details.
