跪拜 Guibai
← Back to the summary

For AI Agents, Organize Frontend by Page, Not by Type: Vertical Slices Cut File Reads by 62.5%

Core conclusion: Traditional frontend components/, styles/, hooks/, utils/ layering is horizontal by type. Changing one page's interaction means jumping between four or five directories. In the AI Agent era, the better approach is vertical slicing by page: one URL maps to one page directory, with page structure, page CSS, and page JS all inside, and no references between pages. Only three kinds of content may be shared across pages: the API service layer, common theme styles, and global toast notifications. For a repo estimated at 20 pages with 5 files per page, a single change drops from 8 files read to 3, a reduction of 62.5%. Code volume will grow in the short term, but the editor is now an AI instead of a human; file-read count and context usage are the real cost.


Table of Contents


1. Conclusion First: Vertical Slice by Page

State the conclusion first, then explain why.

The organizing axis changes from "file type" to "business page". Before, it was "all components in one place, all styles in one place"; now it is "everything for the home page in one place, everything for the orders page in one place". There is only one judgment criterion: to change a page, do you need to open another page's directory? You should not.

The shared layer converges into a whitelist. Only three things can cross pages: the API service layer that calls the backend, common theme styles (theme), and global toast notifications. If a fourth shared item appears outside the whitelist, ask: "Is this truly shared, or is it actually this page's own concern?"

The modification radius shrinks from "repo" to "directory". Where there is a problem, change it there. The AI only needs to read the directory where the problem occurs, plus one or two shared files.

This idea is known in the industry as vertical slice architecture, also called feature-based organization, which is orthogonal to type-based organization. It is not a new invention, but under the premise that "the modifier is an AI", the cost structure changes: humans read code by how maintainable the repo is, while AI reads code by how many files it must read for one task. The two optimal solutions are different.

References that introduced this idea:


2. Why Horizontal Layering Is Slow in AI's Hands (Type-based Layering)

The original motive of horizontal layering is reuse: the same button component is shared by ten pages, and one change applies site-wide. In the era of human-written code, this calculation works: a human changes a button once, and the cost is "find it + change it", and finding it relies only on memory and IDE navigation.

The problem is that AI has no memory, only a context window. The thing it needs to find does not automatically appear; it must be read in before it is known. This turns "where files are scattered" from a navigation problem into a cost problem.

Look at a concrete scenario: clicking the "cancel order" button on the orders page does nothing.

In a type-layered repo, this chain crosses five directories:

  1. routes/orders.tsx — page structure, where the button is attached
  2. components/Button.tsx — the button component itself
  3. hooks/useCancelOrder.ts — the logic after clicking
  4. api/order.ts — where the request is actually sent
  5. styles/orders.css — the disabled-state style for the button

The safest way for the AI to diagnose is to read all five, plus global toast and theme variables. That is 7 to 8 files. Each file is not large, but there are no information boundaries between them: you cannot tell from the directory structure which files belong to the orders page; you can only guess from file names.

Metaphor 🍱: horizontal layering is like a warehouse sorted by material: all screws on shelf 1, all boards on shelf 2, all paint on shelf 3. To assemble a chair, you must visit all five shelves; leftover scraps afterward are unclear which shelf they go back to. Vertical slicing is like prep boxes for dishes: one box holds all ingredients for one dish; the chef reaches in, and when done, throws the whole box away.


3. What the New Structure Looks Like (Directory Layout)

A typical vertical slice directory tree:

src/
├── pages/                        # Page layer: one URL, one directory, no references between them
│   ├── home/
│   │   ├── page.js               # Home page structure + logic
│   │   ├── page.css              # Home page styles, only applies to home
│   │   └── page.test.js          # Home page's own tests
│   ├── orders/
│   │   ├── page.js               # Orders page structure + logic
│   │   ├── page.css              # Orders page styles
│   │   └── page.test.js
│   └── settings/
│       ├── page.js
│       └── page.css
├── shared/                       # Shared layer: whitelist, only three types
│   ├── api/                      # ① Backend API calls
│   │   ├── order.js
│   │   └── user.js
│   ├── theme.css                 # ② Theme variables and global reset
│   └── toast.js                  # ③ Global toast notifications
└── router.js                     # Route table: URL → page directory, centrally maintained

Three constraints hold this tree up:

One page, one directory. Every file in pages/orders/ exists to "make the orders page run"; no file serves three pages. Pages are forbidden from importing each other; reuse goes through the shared layer, or simply duplicate.

Styles colocated nearby (colocation). page.css and page.js sit in the same directory; when changing styles you don't guess which styles file it is, and you don't accidentally affect other pages, because this CSS is only imported by this page.

Router table independent. router.js is the only place that knows "which pages exist". Adding a page = adding a directory + a route line; deleting a page = deleting a directory + a route line, leaving no orphaned styles or hooks.

Under this structure, the diagnosis radius for "cancel order button does not respond" is: pages/orders/page.js + shared/api/order.js, at most one more look at shared/toast.js.


4. Shared Layer Keeps Only Three Types (Shared Layer Boundary)

The easiest place to break vertical slicing is the shared layer. After the first page is written, someone always says "this formatting function is used by three pages, put it in shared", then a second and third follow, and six months later shared/utils/ has grown into a new utils/.

So the shared layer must be whitelist-based, only three types:

Category What goes in Why it must be shared
API service layer Request wrappers, interface definitions, error code mappings The backend contract has only one copy; writing it per page inevitably causes inconsistency
Common theme CSS variables, fonts, spacing, light/dark themes Site-wide visuals must be uniform, there can only be one source of truth
Global toast toast, confirm, loading overlay Only one notification can be on screen at a time, naturally global

For anything outside the whitelist that wants to enter the shared layer, pass three questions first:

  1. Is it used by only two or three pages? If so, prefer copying it twice. Consider extraction only for three or more.
  2. Will it change because of one page's requirement? If yes, it is not a general capability; it is that page's business logic.
  3. If deleted, how many directories need code changes? If the answer is "a dozen", it has already become horizontal coupling, not sharing.

This line is called the rule of three: write it directly the first time, copy it the second, abstract it the third. When humans write code this rule is often treated as a style suggestion; in the AI era it is cost discipline: for every additional file in the shared layer, each related page's modification requires reading one more file, and reading is the AI's only overhead.

A note on the theme layer: it coexists with per-page styles, and the order must be theme first, page second, otherwise page styles won't get the variable values. This layering has a full implementation in Why a unified theme.css is needed in frontend projects; this article only emphasizes the boundary: theme holds only variables and resets, never class names for specific pages.


5. A Calculable Account: 8 Files Down to 3 (Context Locality)

"AI changes faster" without numbers is just a slogan. This account can be recalculated yourself.

Assumptions (state the premises clearly; numbers only then make sense):

Type-based layering: to change one page interaction, the safe approach is reading 5 page-related files + 3 shared files = 8 files, about 9600 tokens.

Vertical slicing: the same change reads this page's page.js and page.css, plus one relevant shared/api/order.js = 3 files, about 3600 tokens.

Reduction:

$$ \frac{8 - 3}{8} = 62.5% $$

Token usage drops from 9600 to 3600, saving 6000. The meaning of this number is not precision, but that it can be challenged and corrected: if each page has only 3 files, the reduction is smaller; if each page is scattered across 8 directories, it is larger. The real determinant of benefit is "how many directories one page spans", and that is exactly the cut the new structure makes.

There is also a benefit not reflected in the formula: context pollution. Among the 8 files there are inevitably styles and logic from other pages; the more the model reads, the more scattered its attention is, and the more likely it is to copy orders-page patterns into the settings page. Reading only 3 files that all belong to one page significantly lowers cross-page contamination.


6. Code Volume Grows Short-term, Shrinks Long-term (Code Volume)

This is the most counterintuitive point in the whole plan, and it must be explained 🔍.

Short-term it does grow. Continuing from the previous section's repo: under type-based layering, 20 pages share one Button, one Table, one formatting function, roughly 9000 lines total; after switching to vertical slices, each page writes its own copy and shared parts are duplicated, total volume rises to around 12000 lines, roughly a 30% increase.

Knowing it grows and still doing it, three reasons (this is a trade-off with known costs, so it must be stated clearly rather than avoided):

First, AI cost does not look at total repo lines; it looks at per-read volume. The model is not more expensive because the repo has 12000 lines; it only charges for the portion you put into context this time. The repo growing from 9000 to 12000 lines, while per-read volume drops from 9600 tokens to 3600 tokens. Total lines and per-task cost are two different curves.

Second, the cost of abstraction is repriced. Horizontal sharing is essentially "exchange coupling for duplication". When humans modify code, coupling is cheap: changing one place and having it take effect site-wide feels great. But the price of coupling is that the modification radius becomes O(page count): once the Button shared by 20 pages needs a loading prop, you may need regression-test 20 pages. Vertical slicing trades this O(20) regression risk for per-page duplicated code. For an executor that must re-read files on every change, this exchange is worthwhile.

Third, deletion is clean. When a requirement goes offline, vertical slicing only needs to delete one directory and all related code disappears with it; horizontal layering leaves unreferenced components, styles, and hooks that lie in the repo for years, get hit by every AI search, and gradually become noise. Shrinking long-term means this: not that total code volume decreases, but that the share of effective code rises and dead code stops accumulating.

One sentence to summarize this trade-off: duplication costs "a few extra lines", coupling costs "reading and understanding a whole area every change". When the marginal cost of writing code approaches zero, the former's price drops to almost negligible.


7. A Directly Runnable Vertical Slice (Runnable Slice)

This is zero-dependency and directly runnable. Save it as server.mjs, execute node server.mjs, open http://localhost:3000 to see two independent page slices. It auto-generates the example directory tree on first run; no manual file creation needed.

// server.mjs — zero-dependency service organized by "page vertical slice", run with node server.mjs
import { createServer } from 'node:http'                                        // Node built-in http, no framework
import { readFile, mkdir, writeFile } from 'node:fs/promises'                   // read/write slice and shared layer files
import { existsSync } from 'node:fs'                                            // check if first run to generate examples
import { join, dirname } from 'node:path'                                       // cross-platform path joining
import { fileURLToPath, pathToFileURL } from 'node:url'                         // dynamic import requires file URL

const ROOT = dirname(fileURLToPath(import.meta.url))                            // project root is this file's directory

// Route table: URL → page directory name, one-to-one, look at the table to know which page to change
const ROUTES = {
  '/': 'home',                                                                  // home → pages/home/
  '/orders': 'orders',                                                          // orders → pages/orders/
}

// First run generates two page slices + three shared files, so copy-paste runs
async function ensureDemo() {
  if (existsSync(join(ROOT, 'pages'))) return                                    // directory already exists, don't overwrite your changes
  const files = {
    'shared/theme.css': ':root{--bg:#fff;--fg:#1f2937;--accent:#22c55e}\nbody{background:var(--bg);color:var(--fg);font-family:system-ui}\n', // ② common theme
    'shared/api.js': 'export async function listOrders(){return [{id:1,total:99},{id:2,total:120}]}\n',                                      // ① API service layer
    'shared/toast.js': 'export function toast(t){return `<div class="toast">${t}</div>`}\n',                                                 // ③ global toast
    'pages/home/page.js': 'export default function page(){return {title:"首页",html:`<h1>首页</h1><p><a href="/orders">去订单页</a></p>`}}\n', // home slice
    'pages/home/page.css': 'h1{color:var(--accent)}\n',                                                                                      // home styles only apply to home
    'pages/orders/page.js': 'import { listOrders } from "../../shared/api.js"\nimport { toast } from "../../shared/toast.js"\nexport default async function page(){const rows=await listOrders()\nreturn {title:"订单",html:`<h1>订单</h1><ul>${rows.map(r=>`<li>#${r.id} ¥${r.total}</li>`).join("")}</ul>${toast("已加载 "+rows.length+" 条")}`}}\n', // orders slice
    'pages/orders/page.css': 'ul{padding-left:1rem}\n.toast{color:var(--accent)}\n',                                                          // orders styles
  }
  for (const [p, body] of Object.entries(files)) {                               // write each file: the path itself is the convention
    await mkdir(dirname(join(ROOT, p)), { recursive: true })                     // create directories recursively if missing
    await writeFile(join(ROOT, p), body)                                         // write minimal runnable content
  }
}

// Render one page: only touches three things — this page's page.js, page.css, and the shared layer
async function renderPage(name) {
  const dir = join(ROOT, 'pages', name)                                          // this page's own directory
  const { default: page } = await import(pathToFileURL(join(dir, 'page.js')).href) // page logic is in its own directory
  const view = await page()                                                      // each page decides its own data
  const pageCss = await readFile(join(dir, 'page.css'), 'utf8')                  // this page's styles also in its own directory
  const themeCss = await readFile(join(ROOT, 'shared', 'theme.css'), 'utf8')     // theme variables come from the only shared layer
  return `<!doctype html><html><head><meta charset="utf-8"><title>${view.title}</title>
<style>${themeCss}\n${pageCss}</style></head><body>${view.html}</body></html>`   // theme first, page styles after
}

const server = createServer(async (req, res) => {                               // one URL in, only finds its own directory
  const name = ROUTES[req.url.split('?')[0]]                                    // map URL to directory name via route table
  if (!name) { res.writeHead(404).end('not found'); return }                     // no matching page, return 404
  res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })             // pages uniformly return HTML
  res.end(await renderPage(name))                                               // render and send to browser
})

await ensureDemo()                                                               // ensure example directories exist first
server.listen(3000, () => console.log('http://localhost:3000'))                  // open browser to see two slices

After running it, notice three things, which are the entire point of this structure:


8. Symptom → Cause → Solution Table (Symptom Table)

Symptom Cause Solution
Changing one button, AI searches 5 directories and still can't locate it Files are scattered horizontally by type, the directory structure doesn't express ownership One URL per directory, page structure / CSS / JS colocated
AI changed page A, page B's styles changed too Shared CSS mixes in page-specific class names Page styles go into page.css, shared layer holds only variables and resets
shared/ becomes a second utils/ six months later Shared layer has no admission criteria, anything gets thrown in Whitelist only API / theme / toast, handle the rest by rule of three
AI reads a dozen files in one task, starts "forgetting" earlier content midway Modification radius spans the whole repo, context is crowded by unrelated code Compress modification radius to one directory + 1 shared file
Requirement goes offline, deleting the page leaves a pile of dead code Page code is scattered, deletion can't be atomic Delete one directory to take the page offline, synchronously delete one route line
Duplicating a formatting function per page feels awkward Actively trading duplication for low coupling Accept duplication: AI-side cost depends on read volume, not repo line count
Pages start importing each other Boundary not held, vertical slice degenerates into horizontal coupling Forbid cross-page references, all sharing goes through the shared layer whitelist

9. Five Implementation Pitfalls (Pitfalls)

Pitfall one: the shared layer only includes API, forgetting theme and toast are also shared. Each page ends up writing its own toast, with inconsistent styles and placement. The three shared types have intrinsic reasons; they aren't arbitrarily chosen.

Pitfall two: treating "common components" as the shared layer. Button, Table, Modal look like they should be shared, but once twenty pages depend on them, changing one requires regression-testing twenty pages. The right move is to copy them into each page and let each page evolve on its own; extract only when three or more pages genuinely require an identical implementation.

Pitfall three: stuffing things that don't belong into a page directory. For example, putting "date formatting used only by the orders page" into pages/orders/utils/ is fine; but if this utils/ starts being imported by other pages, the boundary is broken. The judgment criterion remains: does this file serve only this one page?

Pitfall four: the router table and directories go out of sync. Adding a directory but forgetting the route, or deleting a page but forgetting the route, leaves a 404. Treat the router table as the single entry point: when adding a page, first change the route table, then create the directory.

Pitfall five: style priority conflicts. Theme, page styles, and component inline styles stack three layers; "changed but doesn't take effect" is common. Establish a fixed order: theme variables → page styles → runtime overrides, and page styles should use only class selectors, not tag selectors or !important.


10. Criteria: To Slice or Not to Slice (Verdict)

When is it worth switching to vertical slicing:

When not to switch, or only partially:

If you decide to switch, don't do a one-time refactor. Pick a page currently being changed, move it into the new structure, then after it works, move the next. After moving three pages, you will have a completely different judgment on "what really belongs in the shared layer".

When page boundaries are clear, the shared layer has only three types, and one change only reads one directory, this structure is worth using; when pages are few, or component consistency is the core demand, horizontal layering is still more appropriate. Don't do structure for structure's sake.

This column, "Full-Stack Development in Practice", goes from project structure and style systems to front-end/back-end integration and deployment, each article with runnable code and a symptom table, updated weekly. To read in order, subscribe on the column page.