Interface definition specification
Component development and interface definition are core aspects of front-end engineering. The formulation of standards directly impacts code maintainability and team collaboration efficiency. From component design principles to interface conventions, clear guidelines are needed to constrain development practices, avoiding issues like inconsistent styles or excessive communication overhead.
Component Development Standards
File Structure Conventions
Adopt a flat directory structure, with each component as an independent package. Example structure:
components/
├─ button/
│ ├─ index.tsx // Main entry
│ ├─ style.module.scss
│ ├─ Button.test.tsx
│ └─ README.md // Component documentation
Naming Rules
- PascalCase for component files:
DatePicker.tsx
- kebab-case for style files:
date-picker.module.scss
- Test file suffix:
ComponentName.test.tsx
Props Design Principles
- Keep props atomic; avoid omnipotent props:
// Bad practice
interface Props {
variant: 'text' | 'outlined' | 'contained'
}
// Good practice
interface Props {
text?: boolean
outlined?: boolean
contained?: boolean
}
- Place required props first, optional props last:
interface ModalProps {
open: boolean
title: string
onClose?: () => void
width?: number
}
State Management
- Use
useState
/useReducer
for internal component state. - Encapsulate complex state logic as custom hooks:
function useToggle(initial = false) {
const [state, setState] = useState(initial)
const toggle = useCallback(() => setState(v => !v), [])
return [state, toggle] as const
}
Styling Approach
- Prefer CSS Modules over global styles.
- Centralize design variables:
// variables.scss
$primary-color: #1890ff;
$breakpoint-md: 768px;
Interface Definition Standards
RESTful Conventions
- Use plural nouns for resource naming:
GET /api/users
POST /api/articles
- Standardize status codes:
- 200 OK - Standard success response
- 201 Created - Resource created successfully
- 400 Bad Request - Parameter validation failed
- 401 Unauthorized - Unauthenticated
- 403 Forbidden - No permission
Request/Response Formats
- Use JSON for request bodies:
{
"user": {
"email": "user@example.com",
"password": "securepassword"
}
}
- Standard response wrapper:
interface ApiResponse<T> {
code: number
data: T
message?: string
timestamp: number
}
TypeScript Interface Definitions
- Use generics for paginated data:
interface Pagination<T> {
current: number
pageSize: number
total: number
items: T[]
}
interface User {
id: string
name: string
avatar?: string
}
type UserListResponse = ApiResponse<Pagination<User>>
- Parameter validation types:
interface CreateUserParams {
username: string
password: string
age?: number
readonly createdAt: Date
}
Error Handling
- Define error code enums:
enum ErrorCodes {
INVALID_TOKEN = 1001,
RESOURCE_NOT_FOUND = 2004,
DUPLICATE_ENTRY = 3009
}
- Frontend error interception example:
axios.interceptors.response.use(
response => response,
error => {
if (error.response?.status === 401) {
router.push('/login')
}
return Promise.reject(error)
}
)
Version Control Strategy
API Version Management
- URL path versioning:
/api/v1/users
/api/v2/users
- Request header versioning:
GET /api/users
Accept-Version: 1.1.0
Component Version Management
- Follow semantic versioning:
- MAJOR: Incompatible API changes
- MINOR: Backward-compatible feature additions
- PATCH: Backward-compatible bug fixes
- Example changelog:
## 1.2.0 (2023-08-15)
### Features
- Added dark mode support
- Added keyboard navigation
### Fixes
- Fixed dropdown positioning issue (#123)
Documentation Requirements
Component Documentation
-
Props table example: | Prop Name | Type | Default | Description | |-------|------|-------|------| | size | 'small'|'medium'|'large' | 'medium' | Controls button size | | block | boolean | false | Whether to fill container width |
-
Code example display:
<Button
type="primary"
onClick={() => alert('Confirmed')}
>
Confirm Action
</Button>
API Documentation
- Swagger annotation example:
paths:
/users/{id}:
get:
tags: [User]
parameters:
- $ref: '#/parameters/userId'
responses:
200:
description: User details
schema:
$ref: '#/definitions/User'
- Example API response:
{
"code": 200,
"data": {
"id": "usr_123",
"name": "John Doe",
"email": "john@example.com"
},
"timestamp": 1692086400000
}
Performance Optimization Highlights
Component Level
- Avoid unnecessary re-renders:
const MemoComponent = React.memo(Component, (prev, next) => {
return prev.value === next.value
})
- Virtual scroll implementation:
<VirtualList
itemHeight={40}
itemCount={1000}
renderItem={({ index, style }) => (
<div style={style}>Row {index}</div>
)}
/>
API Level
- Default pagination parameters:
interface ListParams {
page?: number
size?: number
sort?: string
}
const DEFAULT_PAGE_SIZE = 20
- Response compression configuration:
server {
gzip on;
gzip_types application/json;
}
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn