阿里云主机折上折
  • 微信号
Current Site:Index > Interface definition specification

Interface definition specification

Author:Chuan Chen 阅读数:20791人阅读 分类: 前端综合

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

  1. Keep props atomic; avoid omnipotent props:
// Bad practice
interface Props {
  variant: 'text' | 'outlined' | 'contained'
}

// Good practice
interface Props {
  text?: boolean
  outlined?: boolean
  contained?: boolean
}
  1. 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

  1. Prefer CSS Modules over global styles.
  2. Centralize design variables:
// variables.scss
$primary-color: #1890ff;
$breakpoint-md: 768px;

Interface Definition Standards

RESTful Conventions

  1. Use plural nouns for resource naming:
GET /api/users
POST /api/articles
  1. 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

  1. Use JSON for request bodies:
{
  "user": {
    "email": "user@example.com",
    "password": "securepassword"
  }
}
  1. Standard response wrapper:
interface ApiResponse<T> {
  code: number
  data: T
  message?: string
  timestamp: number
}

TypeScript Interface Definitions

  1. 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>>
  1. Parameter validation types:
interface CreateUserParams {
  username: string
  password: string
  age?: number
  readonly createdAt: Date
}

Error Handling

  1. Define error code enums:
enum ErrorCodes {
  INVALID_TOKEN = 1001,
  RESOURCE_NOT_FOUND = 2004,
  DUPLICATE_ENTRY = 3009
}
  1. 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

  1. URL path versioning:
/api/v1/users
/api/v2/users
  1. Request header versioning:
GET /api/users
Accept-Version: 1.1.0

Component Version Management

  1. Follow semantic versioning:
  • MAJOR: Incompatible API changes
  • MINOR: Backward-compatible feature additions
  • PATCH: Backward-compatible bug fixes
  1. 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

  1. Props table example: | Prop Name | Type | Default | Description | |-------|------|-------|------| | size | 'small'|'medium'|'large' | 'medium' | Controls button size | | block | boolean | false | Whether to fill container width |

  2. Code example display:

<Button 
  type="primary" 
  onClick={() => alert('Confirmed')}
>
  Confirm Action
</Button>

API Documentation

  1. Swagger annotation example:
paths:
  /users/{id}:
    get:
      tags: [User]
      parameters:
        - $ref: '#/parameters/userId'
      responses:
        200:
          description: User details
          schema:
            $ref: '#/definitions/User'
  1. Example API response:
{
  "code": 200,
  "data": {
    "id": "usr_123",
    "name": "John Doe",
    "email": "john@example.com"
  },
  "timestamp": 1692086400000
}

Performance Optimization Highlights

Component Level

  1. Avoid unnecessary re-renders:
const MemoComponent = React.memo(Component, (prev, next) => {
  return prev.value === next.value
})
  1. Virtual scroll implementation:
<VirtualList
  itemHeight={40}
  itemCount={1000}
  renderItem={({ index, style }) => (
    <div style={style}>Row {index}</div>
  )}
/>

API Level

  1. Default pagination parameters:
interface ListParams {
  page?: number
  size?: number
  sort?: string
}

const DEFAULT_PAGE_SIZE = 20
  1. Response compression configuration:
server {
  gzip on;
  gzip_types application/json;
}

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

上一篇:目录结构规范

下一篇:Git核心知识点

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.