跪拜 Guibai
← Back to the summary

Frontend Architecture for the AI Era: From Code Organization to Feature Abstraction

Part 2 · Architecture Design

From Code Organization to Feature Abstraction: Frontend Engineering Architecture in the AI Era

1. Why Pay Attention to a Frontend Project's Internal Architecture?

In real project development, we often encounter situations like this:

As business features keep growing, the initially simple project directory gradually becomes complex. CSS styles pile up, JS file responsibilities become increasingly blurry, common components and business components get mixed together, and the way third-party component libraries are used gradually becomes inconsistent.

At the same time, the project may also show:

These problems look scattered, but they are all related to the engineering organization and architecture design inside the frontend project.

I believe frontend architecture design does not necessarily have to start with large-system decomposition, micro-frontends, or a complex technical ecosystem.

For actual developers, file organization, code encapsulation, style management, feature abstraction, resource management, and build optimization inside the project are equally important architectural capabilities.

The purpose of architecture design is not to give the project more directories and abstraction layers, but to make the code easier to understand, features easier to reuse, problems easier to locate, and the project able to be continuously maintained and evolved.

2. Project Directory and File Organization Design

The directory structure is the foundation of the entire frontend project.

A reasonable directory structure should not only distinguish file types, but also consider the responsibility relationships and ownership relationships between files.

For example:

src/
├── api/                  # Request and API management
├── assets/               # Static resources
├── components/           # Global common components
├── composables/          # Common composable logic
├── config/               # Unified project configuration
├── hooks/                # Common Hooks
├── layouts/              # Page layouts
├── modules/              # Business modules
├── router/               # Route management
├── services/             # Third-party services and SDKs
├── store/                # Global state
├── styles/               # Global styles
├── utils/                # Common utility functions
├── App.vue
└── main.ts

public/                   # Public static resources

Two organization approaches can be used here:

Organize by file type: For example, centrally manage CSS, JS, utility functions, and common components.

Organize by business module: For example, modules such as device management, user management, and project management, each with its pages, components, APIs, and business logic placed in corresponding directories.

For medium and large projects, I prefer a combination of both.

Globally shared capabilities are managed uniformly, while functions within a business are organized as locally as possible.

This makes shared capabilities easy to reuse and avoids excessively scattering business code.

3. JavaScript / TypeScript File Management

JS and TS are the core logic carriers of a frontend project.

As the project grows, file management needs to gradually shift from simple code accumulation to organization by responsibility.

Key considerations:

For example, a device management module can be organized as follows:

modules/
└── device/
    ├── pages/
    ├── components/
    ├── hooks/
    ├── api/
    ├── utils/
    ├── types/
    └── index.ts

Pages handle business display and interaction, APIs handle interface communication, Hooks handle reusable reactive logic, Utils handle pure functions, and Types handle data structure definitions.

The purpose of file splitting is to make responsibilities clearer, not to add directory layers.

4. CSS Engineering and Style Management

CSS may not be an obvious problem in small projects, but in long-term iterated projects, style management often becomes one of the higher-cost areas of maintenance.

For example:

Therefore, a reasonable CSS file management system should be established.

For example:

styles/
├── index.scss
├── reset.scss
├── variables.scss
├── mixins.scss
├── common.scss
├── themes/
│   ├── light.scss
│   └── dark.scss
└── modules/
    ├── layout.scss
    └── animation.scss

CSS can be divided into several layers:

  1. Base styles: browser default style resets, fonts, etc.
  2. Global styles: globally common layout and helper styles.
  3. Design variables: colors, spacing, fonts, borders, etc.
  4. Theme styles: variable configurations under different themes.
  5. Component styles: managed with the component itself.
  6. Page styles: serve only specific business pages.

At the same time, based on the project's tech stack, SCSS, Less, CSS Variables, and other methods can be used to improve style organization.

5. CSS Style Isolation and Scope Management

Style isolation is a very important part of component-based development.

Especially in multi-developer collaboration and large projects, there may be the same CSS class names across different pages and components, causing styles to override each other.

Common approaches include:

Different methods have different use scenarios, and a higher degree of isolation is not always better.

Real projects also need to consider third-party component style overrides, dynamic components, Teleport, global theme variables, and necessary style sharing between components.

The core goal of style isolation is to make components as independent as possible while preserving necessary style extension capabilities.

6. Secondary Encapsulation of Third-Party Component Libraries

In actual development, we often use third-party component libraries such as Element Plus and Ant Design.

However, using the original components directly in all business pages can, in the long run, lead to issues:

Therefore, we can establish our own component encapsulation layer based on the actual project.

For example:

components/
├── base/
│   ├── BaseButton.vue
│   ├── BaseDialog.vue
│   ├── BaseTable.vue
│   └── BaseForm.vue
├── business/
│   ├── UserSelector.vue
│   ├── DeviceSelector.vue
│   └── OrganizationTree.vue
└── index.ts

Here it is necessary to distinguish:

Secondary encapsulation requires special attention not to reimplement all the capabilities of the original third-party component.

For example, when wrapping a Table, we can unify pagination, loading states, and common props, but we should still preserve necessary slots, events, and prop passthrough.

The purpose of encapsulation is to reduce repetitive development costs, not to create new usage barriers.

7. Utility Functions and Common Logic Abstraction

Projects often contain repetitive logic.

Examples are date formatting, data transformation, file download, data validation, permission checks, and so on.

These functions should be reasonably abstracted according to their scope of use.

We need to distinguish:

Do not put all code into Utils.

A reasonable abstraction should have a clear use scenario, not just because a piece of code is long, so it is extracted and wrapped.

8. Route and Page Organization Design

Routing is an important entry point for a frontend application.

As business pages increase, maintaining all route configurations in a single file gradually becomes harder.

Routes can be split by business module:

router/
├── index.ts
├── routes.ts
├── guards.ts
└── modules/
    ├── user.ts
    ├── device.ts
    └── project.ts

Considerations:

Route design is not just about managing page navigation; it also needs to consider the relationship between page lifecycle and business modules.

9. Unified Request and Response Management

Request encapsulation should not simply create an Axios instance.

You can centrally manage the basic capabilities of requests:

api/
├── request.ts
├── interceptors.ts
├── types.ts
└── modules/
    ├── user.ts
    ├── device.ts
    └── project.ts

Unified handling:

Different business modules only need to maintain their own API definitions.

This ensures consistent request conventions and prevents pages from carrying too much network communication logic.

10. Login Entry and Single Sign-On Design

Here we need to distinguish between the login page, identity authentication, and business API authorization.

The frontend is mainly responsible for login flow interaction, authentication redirects, receiving authentication results, and managing the request credentials afterward.

Authentication-related logic can be organized independently:

auth/
├── index.ts
├── login.ts
├── callback.ts
├── token.ts
└── guards.ts

Considerations:

Single sign-on is not simply attaching a Token in the request interceptor.

Authentication protocols, identity verification, and authorization are usually completed by the identity authentication service and the backend together; the frontend is responsible for the corresponding flow integration.

11. Global State and Data Management

As business complexity increases, data management also needs unified planning.

For example:

Data can be classified by usage scope and lifecycle:

Different data should not all be placed into one global state management tool.

Especially for high-frequency real-time data, you need to consider update frequency, subscription relationships, caching strategies, and rendering rhythm.

12. WebSocket and Real-Time Communication Management

For projects involving device monitoring, map display, real-time video, and digital twins, WebSocket is often an important data source.

If each business page independently creates a WebSocket connection, it can lead to duplicate connections, repeated message handling, and incomplete resource cleanup.

A unified communication management layer can be established:

services/
└── websocket/
    ├── manager.ts
    ├── connection.ts
    ├── events.ts
    └── types.ts

Key considerations:

For large volumes of real-time data, Worker, data serialization, and rendering scheduling also need to be considered.

13. Third-Party SDK and Feature Service Encapsulation

As frontend features continue to grow, more and more third-party SDKs are integrated into projects.

For example:

These SDKs should not simply be initialized repeatedly in each page.

A unified loading and service management mechanism can be established based on the actual situation.

Key focus:

Especially for tools with complex lifecycles such as Cesium and Three.js, initialization, operation, and destruction should be incorporated into the module design.

14. Static Resource and Theme Management

Static resources need to be distinguished by purpose.

For example:

Understand the difference between src/assets and public.

The former usually participates in the build process and can be referenced and optimized at the module level; the latter is suitable for static files that need a fixed path and do not need build processing.

Theme management can establish a unified variable system through CSS Variables:

:root {
  --primary-color: #1677ff;
  --background-color: #ffffff;
  --text-color: #333333;
}

[data-theme="dark"] {
  --primary-color: #409eff;
  --background-color: #141414;
  --text-color: #ffffff;
}

Design variables such as colors, fonts, spacing, and borders are managed uniformly to reduce styles scattered across components.

15. Environment Configuration and Path Proxy Design

Projects usually have different environments such as development, testing, and production.

You need to manage uniformly:

For example:

.env.development
.env.test
.env.production

In the development stage, you can use Vite Proxy or other development server proxies to forward frontend requests to the backend service.

In the production environment, forwarding can be done through Nginx reverse proxy, a gateway, or a dedicated resource service.

Also consider:

It must be clear that frontend development proxy is mainly for the development environment. It cannot replace server-side proxy in production, and sensitive information such as keys must not be placed in frontend configuration.

16. Frontend Design Patterns and Code Abstraction

Design patterns are content worth in-depth study in frontend architecture design.

They are not meant to make code look more advanced, but to help solve problems such as repetitive logic, complex conditionals, and module dependencies.

For example:

Design Pattern Frontend Application
Factory pattern Dynamically create different types of components or instances
Strategy pattern Different business types use different processing logic
Observer pattern Event listening and state change notification
Publish-subscribe pattern WebSocket message dispatch
Adapter pattern Third-party SDK and interface data adaptation
Singleton pattern Global service instance management
Decorator pattern Feature enhancement and behavior extension
Composite pattern Organization of menus, forms, tree components
Proxy pattern Request proxy and object access control

These patterns do not all need to be used.

For example, when multiple business pages have similar conditional checks, the strategy pattern can be considered; when different third-party SDKs provide the same functionality but have inconsistent interfaces, the adapter pattern can be considered.

What really needs to be mastered is:

When is a design pattern needed? What problem does it solve? And what complexity does it introduce after being added?

Design patterns should be a means to solve problems, not a development task in themselves.

17. Frontend Build and Packaging Optimization

Frontend projects ultimately need to be built before they can be deployed to the actual running environment.

As project dependencies and features increase, the build output may become larger, and the initial page load speed may be affected.

Therefore, build optimization is also an important part of frontend engineering architecture.

Key considerations:

1. Build tools and build process

Understand the basic working mechanisms of build tools such as Vite and Webpack, and clarify the differences between development and production builds.

2. Code splitting

Use dynamic import, route lazy loading, and other methods to split out code that does not need to be executed immediately, avoiding all business code being concentrated in one entry file.

3. Tree Shaking

Eliminate unused code through static analysis to reduce the final build output.

4. Third-party dependency optimization

Analyze large dependency libraries, and reasonably use on-demand loading, dependency deduplication, and component-level imports.

5. Static resource optimization

Compress and reasonably process resources such as images, fonts, CSS, and JS.

6. Caching and CDN

Use file hashes, browser caching, and CDN to reduce repeated downloads and improve resource access efficiency.

7. Build output analysis

Use tools such as Bundle Analyzer to analyze bundle size, locate large dependencies and duplicate resources.

8. Multi-environment builds

Unify build configurations for development, testing, and production environments to avoid deployment issues caused by environment differences.

It is also important to note that packaging optimization does not mean pursuing the smallest file size at all costs.

Excessive splitting can produce a large number of network requests, and externalizing third-party dependencies can bring version and loading risks.

True optimization should consider the actual running environment, weighing resource size, loading speed, cache efficiency, and runtime performance.

18. Page Compatibility and Multi-Device Adaptation Design

Frontend projects ultimately run in browsers and various display devices.

Even if the code itself is correct, differences in browsers, screen sizes, resolutions, and runtime environments can cause layout problems or functional incompatibilities.

Therefore, compatibility and adaptation should also be included in engineering design.

1. Browser compatibility

Consider differences between browsers such as Chrome, Firefox, Safari, and Edge, as well as special environments such as domestic browsers and embedded WebViews.

Focus on CSS feature support, JavaScript syntax compatibility, and browser API differences.

2. JavaScript compatibility

Use build tools for syntax downgrading, and configure Babel, Polyfill, and other compatibility solutions based on the actual target browsers.

Note that syntax transformation and API compatibility are two different issues.

3. CSS compatibility

Consider differences in Flex, Grid, positioning, scrollbars, font rendering, and other aspects across different browsers.

4. Screen size adaptation

Use responsive layouts for PC, tablet, and mobile, and reasonably use media queries, Flex, Grid, rem, vw, and other technologies.

5. Multi-resolution adaptation

Handle page layout, fonts, images, and component sizes for display devices with 1080P, 2K, 4K, and different aspect ratios.

6. Large-screen visualization adaptation

For digital twin and data visualization projects, also consider:

7. Component-level adaptation

Common components should not only work normally at one fixed size; they should also work well in different container widths and layout environments.

Compatibility adaptation is not simply making the page displayable, but making functionality and interaction as consistent as possible across different environments.

19. Engineering Architecture Constraints in the AI Programming Era

AI programming is changing the way frontend projects are developed.

Code generation is getting faster and faster, but without clear project specifications, AI can easily produce duplicate encapsulation, wrong dependencies, and unreasonable file organization.

Therefore, the internal architecture of the project also needs to become the constraint foundation for AI programming.

For example:

AI should develop within the existing engineering conventions, rather than redesigning a new structure every time it generates code.

In the future, developers not only need to make AI generate code, but also need to judge whether the generated code fits the project architecture, whether it adds unnecessary complexity, and whether it affects existing functionality.

20. Summary: Architecture Design Is Not About Adding Abstraction

Through these contents, I increasingly feel that frontend engineering architecture design does not need to pursue complexity.

A project can do without micro-frontends, without introducing complex state management, and without establishing an independent component platform.

But it should have clear file organization, reasonable feature encapsulation, unified style management, and clear code dependency relationships.

At the same time, it also needs to consider how the code is finally built, how resources are loaded, and how pages adapt to different browsers and runtime environments.

From source code organization, to module collaboration, to build output and browser runtime, this forms a relatively complete internal architecture design loop for frontend engineering.

I believe that what frontend developers really need to improve in the AI era is not just code implementation ability, but the comprehensive judgment ability for code structure, feature boundaries, engineering costs, and technical solutions.

No single architecture can fit all projects. What truly matters is to choose a design scheme that is cost-effective, maintainable, and can evolve continuously based on the actual needs of the current project.

This article only represents personal thoughts from actual project development. Different projects have different technical backgrounds and business needs. Experienced developers are welcome to supplement and guide.