适用于 TypeScript、JavaScript、React 和 Node.js 开发的通用编码标准、最佳实践和模式。
npx claudepluginhub aaione/everything-claude-code-zhThis skill uses the workspace's default tool permissions.
适用于所有项目的通用编码标准。
Provides coding standards, best practices, and patterns for TypeScript, JavaScript, React, and Node.js. Activate for new projects, code reviews, refactoring, linting setup, and contributor onboarding.
Enforces universal coding standards and best practices for TypeScript, JavaScript, React, and Node.js, including naming conventions, immutability patterns, error handling, and async/await usage. Activates for code reviews, refactoring, and new projects.
Enforces coding standards and best practices for TypeScript, JavaScript, React, and Node.js including naming conventions, immutability patterns, error handling, async/await, and type safety.
Share bugs, ideas, or general feedback.
适用于所有项目的通用编码标准。
// ✅ GOOD: 描述性名称
const marketSearchQuery = 'election'
const isUserAuthenticated = true
const totalRevenue = 1000
// ❌ BAD: 不清楚的名称
const q = 'election'
const flag = true
const x = 1000
// ✅ GOOD: 动词-名词模式
async function fetchMarketData(marketId: string) { }
function calculateSimilarity(a: number[], b: number[]) { }
function isValidEmail(email: string): boolean { }
// ❌ BAD: 不清楚或仅名词
async function market(id: string) { }
function similarity(a, b) { }
function email(e) { }
// ✅ ALWAYS use spread operator
const updatedUser = {
...user,
name: 'New Name'
}
const updatedArray = [...items, newItem]
// ❌ NEVER mutate directly
user.name = 'New Name' // BAD
items.push(newItem) // BAD
// ✅ GOOD: 全面的错误处理
async function fetchData(url: string) {
try {
const response = await fetch(url)
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
}
return await response.json()
} catch (error) {
console.error('Fetch failed:', error)
throw new Error('Failed to fetch data')
}
}
// ❌ BAD: 无错误处理
async function fetchData(url) {
const response = await fetch(url)
return response.json()
}
// ✅ GOOD: 可能时并行执行
const [users, markets, stats] = await Promise.all([
fetchUsers(),
fetchMarkets(),
fetchStats()
])
// ❌ BAD: 不必要的顺序执行
const users = await fetchUsers()
const markets = await fetchMarkets()
const stats = await fetchStats()
// ✅ GOOD: 适当的类型
interface Market {
id: string
name: string
status: 'active' | 'resolved' | 'closed'
created_at: Date
}
function getMarket(id: string): Promise<Market> {
// Implementation
}
// ❌ BAD: 使用 'any'
function getMarket(id: any): Promise<any> {
// Implementation
}
// ✅ GOOD: 带有类型的函数组件
interface ButtonProps {
children: React.ReactNode
onClick: () => void
disabled?: boolean
variant?: 'primary' | 'secondary'
}
export function Button({
children,
onClick,
disabled = false,
variant = 'primary'
}: ButtonProps) {
return (
<button
onClick={onClick}
disabled={disabled}
className={`btn btn-${variant}`}
>
{children}
</button>
)
}
// ❌ BAD: 无类型,不清楚的结构
export function Button(props) {
return <button onClick={props.onClick}>{props.children}</button>
}
// ✅ GOOD: 可重用的自定义 hook
export function useDebounce<T>(value: T, delay: number): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value)
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value)
}, delay)
return () => clearTimeout(handler)
}, [value, delay])
return debouncedValue
}
// 用法
const debouncedQuery = useDebounce(searchQuery, 500)
// ✅ GOOD: 适当的状态更新
const [count, setCount] = useState(0)
// 基于前一个状态的功能性更新
setCount(prev => prev + 1)
// ❌ BAD: 直接状态引用
setCount(count + 1) // Can be stale in async scenarios
###以此渲染
// ✅ GOOD: 清晰的条件渲染
{isLoading && <Spinner />}
{error && <ErrorMessage error={error} />}
{data && <DataDisplay data={data} />}
// ❌ BAD: 三元运算符地狱
{isLoading ? <Spinner /> : error ? <ErrorMessage error={error} /> : data ? <DataDisplay data={data} /> : null}
GET /api/markets # 列出所有市场
GET /api/markets/:id # 获取特定市场
POST /api/markets # 创建新市场
PUT /api/markets/:id # 更新市场 (full)
PATCH /api/markets/:id # 更新市场 (partial)
DELETE /api/markets/:id # 删除市场
# 用于过滤的查询参数
GET /api/markets?status=active&limit=10&offset=0
// ✅ GOOD: 一致的响应结构
interface ApiResponse<T> {
success: boolean
data?: T
error?: string
meta?: {
total: number
page: number
limit: number
}
}
// Success response
return NextResponse.json({
success: true,
data: markets,
meta: { total: 100, page: 1, limit: 10 }
})
// Error response
return NextResponse.json({
success: false,
error: 'Invalid request'
}, { status: 400 })
import { z } from 'zod'
// ✅ GOOD: Schema 验证
const CreateMarketSchema = z.object({
name: z.string().min(1).max(200),
description: z.string().min(1).max(2000),
endDate: z.string().datetime(),
categories: z.array(z.string()).min(1)
})
export async function POST(request: Request) {
const body = await request.json()
try {
const validated = CreateMarketSchema.parse(body)
// 使用验证后的数据继续
} catch (error) {
if (error instanceof z.ZodError) {
return NextResponse.json({
success: false,
error: 'Validation failed',
details: error.errors
}, { status: 400 })
}
}
}
src/
├── app/ # Next.js App Router
│ ├── api/ # API routes
│ ├── markets/ # Market pages
│ └── (auth)/ # Auth pages (route groups)
├── components/ # React components
│ ├── ui/ # Generic UI components
│ ├── forms/ # Form components
│ └── layouts/ # Layout components
├── hooks/ # Custom React hooks
├── lib/ # Utilities and configs
│ ├── api/ # API clients
│ ├── utils/ # Helper functions
│ └── constants/ # Constants
├── types/ # TypeScript types
└── styles/ # Global styles
components/Button.tsx # PascalCase 用于组件
hooks/useAuth.ts # camelCase 带有 'use' 前缀
lib/formatDate.ts # camelCase 用于工具
types/market.types.ts # camelCase 带有 .types 后缀
// ✅ GOOD: 解释 WHY (为什么), 而不是 WHAT (什么)
// Use exponential backoff to avoid overwhelming the API during outages
const delay = Math.min(1000 * Math.pow(2, retryCount), 30000)
// Deliberately using mutation here for performance with large arrays
items.push(newItem)
// ❌ BAD: 陈述显而易见的事实
// Increment counter by 1
count++
// Set name to user's name
name = user.name
/**
* 使用语义相似度搜索市场。
*
* @param query - 自然语言搜索查询
* @param limit - 最大结果数 (default: 10)
* @returns 按相似度得分排序的市场数组
* @throws {Error} 如果 OpenAI API 失败或 Redis 不可用
*
* @example
* ```typescript
* const results = await searchMarkets('election', 5)
* console.log(results[0].name) // "Trump vs Biden"
* ```
*/
export async function searchMarkets(
query: string,
limit: number = 10
): Promise<Market[]> {
// Implementation
}
import { useMemo, useCallback } from 'react'
// ✅ GOOD: Memoize 昂贵的计算
const sortedMarkets = useMemo(() => {
return markets.sort((a, b) => b.volume - a.volume)
}, [markets])
// ✅ GOOD: Memoize 回调
const handleSearch = useCallback((query: string) => {
setSearchQuery(query)
}, [])
import { lazy, Suspense } from 'react'
// ✅ GOOD: 懒加载重组件
const HeavyChart = lazy(() => import('./HeavyChart'))
export function Dashboard() {
return (
<Suspense fallback={<Spinner />}>
<HeavyChart />
</Suspense>
)
}
// ✅ GOOD: 仅选择需要的列
const { data } = await supabase
.from('markets')
.select('id, name, status')
.limit(10)
// ❌ BAD: 选择一切
const { data } = await supabase
.from('markets')
.select('*')
test('calculates similarity correctly', () => {
// Arrange
const vector1 = [1, 0, 0]
const vector2 = [0, 1, 0]
// Act
const similarity = calculateCosineSimilarity(vector1, vector2)
// Assert
expect(similarity).toBe(0)
})
// ✅ GOOD: 描述性测试名称
test('returns empty array when no markets match query', () => { })
test('throws error when OpenAI API key is missing', () => { })
test('falls back to substring search when Redis unavailable', () => { })
// ❌ BAD: 模糊的测试名称
test('works', () => { })
test('test search', () => { })
注意这些反模式:
// ❌ BAD: Function > 50 lines
function processMarketData() {
// 100 lines of code
}
// ✅ GOOD: 拆分成更小的函数
function processMarketData() {
const validated = validateData()
const transformed = transformData(validated)
return saveData(transformed)
}
// ❌ BAD: 5+ levels of nesting
if (user) {
if (user.isAdmin) {
if (market) {
if (market.isActive) {
if (hasPermission) {
// Do something
}
}
}
}
}
// ✅ GOOD: Early returns
if (!user) return
if (!user.isAdmin) return
if (!market) return
if (!market.isActive) return
if (!hasPermission) return
// Do something
// ❌ BAD: Unexplained numbers
if (retryCount > 3) { }
setTimeout(callback, 500)
// ✅ GOOD: Named constants
const MAX_RETRIES = 3
const DEBOUNCE_DELAY_MS = 500
if (retryCount > MAX_RETRIES) { }
setTimeout(callback, DEBOUNCE_DELAY_MS)
记住:代码质量不可协商。清晰、可维护的代码能够实现快速开发和自信的重构。