← 返回列表
全部 Skill›工具 Tools›coding-standards

coding-standards

作者 @affaan-m · 语言 zh
Universal coding standards, best practices, and patterns for TypeScript, JavaScript, React, and Node.js development.
工具 Tools命令行工具通用访问网络
存储库
最近源活动
—
检测 SKILL.md 语言
zh
星标 ★
308,486
分支 Fork
0
安装选项
提示
指令
使用 AI 助手安装
将下面的提示复制到你正在使用的 AI 助手中。
下载完整 Skill 目录(含全部配套文件)。 下载压缩包 ↓
SKILL.md 原文预览

程式碼標準與最佳實務

適用於所有專案的通用程式碼標準。

程式碼品質原則

1. 可讀性優先

  • 程式碼被閱讀的次數遠多於被撰寫的次數
  • 使用清晰的變數和函式名稱
  • 優先使用自文件化的程式碼而非註解
  • 保持一致的格式化

2. KISS(保持簡單)

  • 使用最簡單的解決方案
  • 避免過度工程
  • 不做過早優化
  • 易於理解 > 聰明的程式碼

3. DRY(不重複自己)

  • 將共用邏輯提取為函式
  • 建立可重用的元件
  • 在模組間共享工具函式
  • 避免複製貼上程式設計

4. YAGNI(你不會需要它)

  • 在需要之前不要建置功能
  • 避免推測性的通用化
  • 只在需要時增加複雜度
  • 從簡單開始,需要時再重構

TypeScript/JavaScript 標準

變數命名

// PASS: 良好:描述性名稱
const marketSearchQuery = 'election'
const isUserAuthenticated = true
const totalRevenue = 1000

// FAIL: 不良:不清楚的名稱
const q = 'election'
const flag = true
const x = 1000

函式命名

// PASS: 良好:動詞-名詞模式
async function fetchMarketData(marketId: string) { }
function calculateSimilarity(a: number[], b: number[]) { }
function isValidEmail(email: string): boolean { }

// FAIL: 不良:不清楚或只有名詞
async function market(id: string) { }
function similarity(a, b) { }
function email(e) { }

不可變性模式(關鍵)

// PASS: 總是使用展開運算符
const updatedUser = {
  ...user,
  name: 'New Name'
}

const updatedArray = [...items, newItem]

// FAIL: 永遠不要直接修改
user.name = 'New Name'  // 不良
items.push(newItem)     // 不良

錯誤處理

// PASS: 良好:完整的錯誤處理
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')
  }
}

// FAIL: 不良:無錯誤處理
async function fetchData(url) {
  const response = await fetch(url)
  return response.json()
}

Async/Await 最佳實務

// PASS: 良好:可能時並行執行
const [users, markets, stats] = await Promise.all([
  fetchUsers(),
  fetchMarkets(),
  fetchStats()
])

// FAIL: 不良:不必要的順序執行
const users = await fetchUsers()
const markets = await fetchMarkets()
const stats = await fetchStats()

型別安全

// PASS: 良好:正確的型別
interface Market {
  id: string
  name: string
  status: 'active' | 'resolved' | 'closed'
  created_at: Date
}

function getMarket(id: string): Promise<Market> {
  // 實作
}

// FAIL: 不良:使用 'any'
function getMarket(id: any): Promise<any> {
  // 實作
}

React 最佳實務

元件結構

// PASS: 良好:具有型別的函式元件
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>
  )
}

// FAIL: 不良:無型別、結構不清楚
export function Button(props) {
  return <button onClick={props.onClick}>{props.children}</button>
}

自訂 Hooks

// PASS: 良好:可重用的自訂 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)

狀態管理

// PASS: 良好:正確的狀態更新
const [count, setCount] = useState(0)

// 基於先前狀態的函式更新
setCount(prev => prev + 1)

// FAIL: 不良:直接引用狀態
setCount(count + 1)  // 在非同步情境中可能過時

條件渲染

// PASS: 良好:清晰的條件渲染
{isLoading && <Spinner />}
{error && <ErrorMessage error={error} />}
{data && <DataDisplay data={data} />}

// FAIL: 不良:三元地獄
{isLoading ? <Spinner /> : error ? <ErrorMessage error={error} /> : data ? <DataDisplay data={data} /> : null}

API 設計標準

REST API 慣例

GET    /api/markets              # 列出所有市場
GET    /api/markets/:id          # 取得特定市場
POST   /api/markets              # 建立新市場
PUT    /api/markets/:id          # 更新市場(完整)
PATCH  /api/markets/:id          # 更新市場(部分)
DELETE /api/markets/:id          # 刪除市場

# 過濾用查詢參數
GET /api/markets?status=active&limit=10&offset=0

回應格式

// PASS: 良好:一致的回應結構
interface ApiResponse<T> {
  success: boolean
  data?: T
  error?: string
  meta?: {
    total: number
    page: number
    limit: number
  }
}

// 成功回應
return NextResponse.json({
  success: true,
  data: markets,
  meta: { total: 100, page: 1, limit: 10 }
})

// 錯誤回應
return NextResponse.json({
  success: false,
  error: 'Invalid request'
}, { status: 400 })

輸入驗證

import { z } from 'zod'

// PASS: 良好: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 路由
│   ├── markets/           # 市場頁面
│   └── (auth)/           # 認證頁面(路由群組)
├── components/            # React 元件
│   ├── ui/               # 通用 UI 元件
│   ├── forms/            # 表單元件
│   └── layouts/          # 版面配置元件
├── hooks/                # 自訂 React hooks
├── lib/                  # 工具和設定
│   ├── api/             # API 客戶端
│   ├── utils/           # 輔助函式
│   └── constants/       # 常數
├── types/                # TypeScript 型別
└── styles/              # 全域樣式

檔案命名

components/Button.tsx          # 元件用 PascalCase
hooks/useAuth.ts              # hooks 用 camelCase 加 'use' 前綴
评论
Aaffaan-m
affaan-m
affaan-m/ECC
查看 GitHub 仓库 查看作者的其他 Skill
来源信息
作者@affaan-m
所属大类工具 Tools / 命令行工具
国内可用性通用
最近源活动—
风险提示访问网络
提示:风险标签为程序静态扫描结果,仅作提示,不代表安全认证。安装前请阅读 SKILL.md 及其引用的脚本、权限,自行判断是否可信。