AI-Assisted Development for Component-Based E-Commerce Frontends

    This article discusses how to use AI-assisted coding to generate a multi-page e-commerce frontend while keeping routes, permissions, data flow, visual design, form validation, and data access coherent. It covers requirement breakdown, purchase-flow data persistence, visual and responsive consistency, interaction states, pure validation functions, currency calculation, mock-data decoupling, project structure, and a review checklist for generated sites.

    1. Problem Background

    AI-assisted programming has moved from completing a single line of code to generating multi-page projects directly from a requirement description. The difficulty in these tasks is not whether an individual component is correct, but whether the entire site is coherent from end to end. Whether navigation between pages is closed, whether the same button has a consistent style across pages, and whether purchase data can flow from the first page to the last determine whether the site can be demonstrated and used.

    Consider an e-commerce site with ten pages. A typical scope includes product listing, product detail, checkout, order success, login, register, and the account area with overview, orders, wallet (including coupons and cards), and settings. These pages share navigation, authentication state, shopping data, and visual specifications. If any link is missing, users encounter a break in the flow.

    This article does not evaluate specific tools. It discusses how to define requirements, how to accept generated results, and which engineering issues require manual review.

    2. Break Down Requirements Before Generation

    Entering “build an e-commerce site” directly usually produces a result that looks complete but has broken flows. A more effective approach is to break requirements into a checklist that can be verified item by item. Each page should define at least four things: route path, access permission, dependent data, and post-completion action.

    The following route table example shows this approach:

    1. // Route table example: each page declares path, access permission, and dependent data
    2. export const routes = [
    3. { path: "/", name: "Home", auth: false, data: "productList" },
    4. { path: "/product/:id", name: "Product Detail", auth: false, data: "productDetail" },
    5. { path: "/checkout/:id", name: "Checkout", auth: true, data: "orderDraft" },
    6. { path: "/order/success", name: "Order Success", auth: true, data: "orderResult" },
    7. { path: "/login", name: "Login", auth: false },
    8. { path: "/register", name: "Register", auth: false },
    9. { path: "/account/dashboard", name: "Account Overview", auth: true },
    10. { path: "/account/orders", name: "Orders", auth: true, data: "orders" },
    11. { path: "/account/wallet", name: "Wallet and Coupons", auth: true, data: "wallet" },
    12. { path: "/account/settings", name: "Settings", auth: true },
    13. ];

    With a route table, acceptance has a clear basis. During acceptance, check the following: when an unauthenticated user accesses a protected page, does the app redirect to the login page; after login, does the app return to the original page; can the product ID on the detail page be found in the listing data.

    2.1 Data Flow in the Purchase Path

    The purchase path is the most fragile part. After selecting specifications and quantity on the product detail page, the app creates an order draft. The checkout page reads the draft, displays the amount and shipping information, and generates an order ID after submission. The order success page reads only the order ID and processing result.

    If the draft is stored only in page-local state, data is lost after a page refresh. This constraint should be written into the requirements document, and the generated result should be required to store the draft in session storage or global state. During acceptance, refreshing the checkout page once to check whether the product and quantity are retained is a simple and effective test.

    3. Ensure Overall Consistency

    Consistency includes visual, interaction, and engineering aspects. Without unified constraints, generated pages often operate independently. A primary button may use three different colors on the home page, product detail page, and checkout page.

    3.1 Visual Consistency

    Colors, spacing, border radius, and font size should be defined centrally as design variables. Pages should reference variables rather than hard-code values.

    1. :root {
    2. --color-primary: #1f6feb;
    3. --color-text: #1f2937;
    4. --color-on-primary: #ffffff;
    5. --radius-md: 8px;
    6. --space-md: 16px;
    7. }
    8. .btn-primary {
    9. background: var(--color-primary);
    10. color: var(--color-on-primary);
    11. border-radius: var(--radius-md);
    12. padding: var(--space-md);
    13. }

    Button text and background contrast must be checked separately. White text on a white background and light gray text on a light gray background are common defects. Mainstream accessibility standards require a contrast ratio of at least 4.5:1 for normal body text against its background. A contrast checking tool can be used to verify this page by page.

    3.2 Responsive Layout

    Mobile acceptance should cover at least three items: whether navigation collapses on narrow screens, whether form width adapts to the screen, and whether login and register pages become distorted on narrow screens. A common approach is to define breakpoints with media queries and compare screenshots at multiple viewport widths.

    1. .auth-form {
    2. width: 360px;
    3. max-width: 100%;
    4. }
    5. @media (max-width: 480px) {
    6. .auth-form {
    7. width: 100%;
    8. padding: 0 16px;
    9. }
    10. }

    3.3 Interaction States

    Every data page should cover three states: loading, empty, and request failure. Pages that implement only the normal state show a blank area or an error when the network is slow or the API returns an empty result. During acceptance, artificially delay the data request or return an empty array, and observe whether the page provides a reasonable message.

    4. Engineering Implementation of Form Validation

    Login, register, checkout, and settings pages all contain forms. Validation rules should be placed in pure functions and separated from UI rendering. This makes them easier to reuse and easier to unit test.

    1. // utils/validateRegister.js: pure function, independent of UI and network
    2. export function validateRegister(form) {
    3. const errors = {};
    4. if (!/^[\w.-]+@[\w-]+\.[\w.]+$/.test(form.email)) {
    5. errors.email = "Invalid email format";
    6. }
    7. if (form.password.length < 8) {
    8. errors.password = "Password must be at least 8 characters";
    9. }
    10. if (form.password !== form.confirmPassword) {
    11. errors.confirmPassword = "Passwords do not match";
    12. }
    13. return { valid: Object.keys(errors).length === 0, errors };
    14. }

    Two points need emphasis. First, frontend validation only improves user experience. The server must still revalidate the same rules, because frontend code can be bypassed. Second, amount calculation requires particular care. Floating-point numbers produce errors during accumulation. In e-commerce scenarios, amounts should be stored and calculated as integers in the smallest currency unit (cents), and formatting should happen only in the presentation layer.

    1. // Calculate order amount in cents to avoid floating-point errors
    2. export function calcOrderTotal(items) {
    3. const totalCents = items.reduce(
    4. (sum, item) => sum + item.priceCents * item.quantity,
    5. 0
    6. );
    7. return totalCents;
    8. }
    9. export function formatCny(cents) {
    10. return `¥${(cents / 100).toFixed(2)}`;
    11. }

    5. Decouple the Data Layer from Mock Data

    Demo sites usually need mock data. The problem with mock data is that it is easily mixed into page code. When real APIs are integrated later, every page must be modified. The solution is to make pages depend only on data service interfaces, with the service layer deciding the data source.

    1. // services/productService.js: pages call only these functions and do not reference mock data directly
    2. const config = { useMock: true };
    3. export async function fetchProducts() {
    4. if (config.useMock) {
    5. const { mockProducts } = await import("../mock/products.js");
    6. return mockProducts;
    7. }
    8. const res = await fetch("/api/products");
    9. if (!res.ok) {
    10. throw new Error(`Request failed: ${res.status}`);
    11. }
    12. return res.json();
    13. }

    When switching to a real API, only the configuration item needs to change, and page code does not need to be modified. This structure also makes acceptance easier. The check is to search the page directory for any remaining direct references to mock data.

    6. Project Structure and Directory Conventions

    A messy structure directly causes build failures. Common problems include nested directories with the same name, causing import paths to point to the wrong location; and empty directories that contain only a name and no content, indicating that the structure has not actually been implemented. A recommended structure is as follows:

    1. src/
    2. pages/ Page-level components, one directory per route
    3. components/ Shared components reused across pages
    4. services/ Data access, wrapping API and mock-data switching
    5. state/ Global state, such as authentication state and shopping cart
    6. styles/ Design variables and global styles
    7. mock/ Mock data, used only for development and demonstration
    8. utils/ Pure functions such as validation and formatting

    The rules are simple. Each directory must have a clear responsibility. Empty directories should either be filled with content or deleted. Styles can be stored alongside components or centralized in the styles directory, but only one approach should be chosen within the same project.

    7. Common Defects and Review Checklist

    Generated sites commonly have the following defects, and acceptance should check them one by one.

    • All images are placeholders.