Agent skill

Coding Standards

by xu-xiang in xu-xiang/everything-claude-code-zh

适用于 TypeScript、JavaScript、React 和 Node.js 开发的通用编码标准、最佳实践与模式。

MITAuto-check passedDevelopment

Install Coding Standards

skills CLI
$ npx skills add xu-xiang/everything-claude-code-zh --skill coding-standards -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install xu-xiang/everything-claude-code-zh coding-standards --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/xu-xiang/everything-claude-code-zh.git skills-src && mkdir -p .claude/skills && cp -r skills-src/.agents/skills/coding-standards .claude/skills/coding-standards && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
coding-standards
GitHub stars
2k
Token cost
~2.4k tokens
SKILL.md length
110 words
Files
2
Skills in repo
78
Repo updated
First seen
Licence
MIT

At a glance

适用于 TypeScript、JavaScript、React 和 Node.js 开发的通用编码标准、最佳实践与模式。

  • Works in 7 steps: 可读性优先 → KISS (Keep It Simple, Stupid - 保持简单) → DRY (Don't Repeat Yourself - 不要重复自己) → …
  • Tasks that involve Code quality
  • SKILL.md covers 何时激活, 代码质量原则, TypeScript/JavaScript 标准 and React 最佳实践, plus 4 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md

What it does

Coding Standards is an agent skill from xu-xiang/everything-claude-code-zh. 适用于 TypeScript、JavaScript、React 和 Node.js 开发的通用编码标准、最佳实践与模式。

Its SKILL.md is about 2.4k tokens, which your agent loads only when the skill is triggered. The skill folder holds 2 other files (for example `agents/openai.yaml`).

It sits in Development, covering Code quality. It works with JavaScript, TypeScript, React and Node.js. The repository describes itself as: everything-claude-code 中文翻译项目:完整的 Claude Code 配置集合(agents, skills, hooks, commands, rules, MCPs)。源自 Anthropic 黑客松获胜者的实战配置,助力中文工程师高效理解与使用 Claude Code。 The licence is MIT.

When your agent uses it

  • Tasks that involve Code quality

Example prompts

  • “/coding-standards”

Requirements

  • Node.js

Workflow steps

7 steps, taken from the step headings in SKILL.md.

  1. 可读性优先
  2. KISS (Keep It Simple, Stupid - 保持简单)
  3. DRY (Don't Repeat Yourself - 不要重复自己)
  4. YAGNI (You Aren't Gonna Need It - 你不会需要它)
  5. 过长函数
  6. 过深嵌套
  7. 魔术数字 (Magic Numbers)

What it can do on your machine

Read from SKILL.md and the folder at commit dfbf946. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are typescript).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Coding Standards loads about 2.4k tokens when it runs. Until then it costs about 19 tokens; SKILL.md has 110 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~19
When it runs · the whole SKILL.md, loaded when a task matches
~2.4k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from xu-xiang/everything-claude-code-zh at commit dfbf946, republished under its MIT licence (© xu-xiang). 110 words, ~2,367 tokens.

Download SKILL.mdSave it as .claude/skills/coding-standards/SKILL.md (or your agent's skills folder). This skill also uses 1 other file; get the full folder from GitHub.
name
coding-standards
description
适用于 TypeScript、JavaScript、React 和 Node.js 开发的通用编码标准、最佳实践与模式。
origin
ECC

编码标准与最佳实践

适用于所有项目的通用编码标准。

何时激活

  • 开始新项目或模块时
  • 进行代码质量与可维护性审查时
  • 为了遵循约定而重构现有代码时
  • 强制执行命名、格式或结构的一致性时
  • 设置 Lint、格式化或类型检查规则时
  • 引导新贡献者了解编码约定时

代码质量原则

1. 可读性优先
  • 代码被阅读的次数远多于编写的次数
  • 变量和函数命名应清晰明确
  • 优先选择自描述代码而非注释
  • 保持一致的格式
2. KISS (Keep It Simple, Stupid - 保持简单)
  • 采用最简单的可行方案
  • 避免过度工程(Over-engineering)
  • 不要进行过早优化
  • 易于理解胜过奇技淫巧
3. DRY (Don't Repeat Yourself - 不要重复自己)
  • 将公共逻辑提取到函数中
  • 创建可复用的组件
  • 在模块间共享工具函数
  • 避免“复制粘贴式”编程
4. YAGNI (You Aren't Gonna Need It - 你不会需要它)
  • 不要在功能被需要之前就构建它
  • 避免投机性的通用设计
  • 仅在必要时增加复杂度
  • 从简单开始,在需要时重构

TypeScript/JavaScript 标准

变量命名
typescript
// ✅ 推荐:描述性名称
const marketSearchQuery = 'election'
const isUserAuthenticated = true
const totalRevenue = 1000

// ❌ 不推荐:命名不清晰
const q = 'election'
const flag = true
const x = 1000
函数命名
typescript
// ✅ 推荐:动词-名词模式
async function fetchMarketData(marketId: string) { }
function calculateSimilarity(a: number[], b: number[]) { }
function isValidEmail(email: string): boolean { }

// ❌ 不推荐:不清晰或仅用名词
async function market(id: string) { }
function similarity(a, b) { }
function email(e) { }
不可变模式 (Immutability Pattern)(至关重要)
typescript
// ✅ 始终使用展开运算符 (Spread Operator)
const updatedUser = {
  ...user,
  name: 'New Name'
}

const updatedArray = [...items, newItem]

// ❌ 严禁直接修改 (Mutate)
user.name = 'New Name'  // 错误
items.push(newItem)     // 错误
错误处理
typescript
// ✅ 推荐:全面的错误处理
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')
  }
}

// ❌ 不推荐:没有错误处理
async function fetchData(url) {
  const response = await fetch(url)
  return response.json()
}
Async/Await 最佳实践
typescript
// ✅ 推荐:尽可能并行执行
const [users, markets, stats] = await Promise.all([
  fetchUsers(),
  fetchMarkets(),
  fetchStats()
])

// ❌ 不推荐:不必要的顺序执行
const users = await fetchUsers()
const markets = await fetchMarkets()
const stats = await fetchStats()
类型安全
typescript
// ✅ 推荐:定义合适的类型
interface Market {
  id: string
  name: string
  status: 'active' | 'resolved' | 'closed'
  created_at: Date
}

function getMarket(id: string): Promise<Market> {
  // 实现
}

// ❌ 不推荐:使用 'any'
function getMarket(id: any): Promise<any> {
  // 实现
}

React 最佳实践

组件结构
typescript
// ✅ 推荐:带类型的函数式组件
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>
  )
}

// ❌ 不推荐:无类型,结构不清晰
export function Button(props) {
  return <button onClick={props.onClick}>{props.children}</button>
}
自定义 Hook (Custom Hooks)
typescript
// ✅ 推荐:可复用的自定义 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)
状态管理
typescript
// ✅ 推荐:正确的状态更新
const [count, setCount] = useState(0)

// 基于前一个状态的函数式更新
setCount(prev => prev + 1)

// ❌ 不推荐:直接引用当前状态
setCount(count + 1)  // 在异步场景中可能会导致状态过期
条件渲染
typescript
// ✅ 推荐:清晰的条件渲染
{isLoading && <Spinner />}
{error && <ErrorMessage error={error} />}
{data && <DataDisplay data={data} />}

// ❌ 不推荐:三元运算符地狱
{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
响应格式
typescript
// ✅ 推荐:一致的响应结构
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 })
输入校验
typescript
import { z } from 'zod'

// ✅ 推荐: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 Hook
├── lib/                  # 工具函数与配置
│   ├── api/             # API 客户端
│   ├── utils/           # 辅助函数
│   └── constants/       # 常量
├── types/                # TypeScript 类型定义
└── styles/              # 全局样式
文件命名
components/Button.tsx          # 组件使用大驼峰 (PascalCase)
hooks/useAuth.ts              # 以 'use' 为前缀的小驼峰 (camelCase)
lib/formatDate.ts             # 工具函数使用小驼峰 (camelCase)
types/market.types.ts         # 使用小驼峰并以 .types 为后缀

注释与文档

何时编写注释
typescript
// ✅ 推荐:解释“为什么”,而不是“是什么”
// 在服务中断期间使用指数退避 (Exponential Backoff),以避免请求压垮 API
const delay = Math.min(1000 * Math.pow(2, retryCount), 30000)

// 为了优化处理大型数组的性能,这里特意使用了 Mutate 操作
items.push(newItem)

// ❌ 不推荐:描述显而易见的事实
// 计数器加 1
count++

// 将名称设置为用户的名称
name = user.name
公共 API 的 JSDoc
typescript
/**
 * 使用语义相似度搜索市场。
 *
 * @param query - 自然语言搜索查询词
 * @param limit - 最大结果数量(默认: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[]> {
  // 实现
}

性能最佳实践

记忆化 (Memoization)
typescript
import { useMemo, useCallback } from 'react'

// ✅ 推荐:对高开销计算进行记忆化
const sortedMarkets = useMemo(() => {
  return markets.sort((a, b) => b.volume - a.volume)
}, [markets])

// ✅ 推荐:对回调函数进行记忆化
const handleSearch = useCallback((query: string) => {
  setSearchQuery(query)
}, [])
懒加载 (Lazy Loading)
typescript
import { lazy, Suspense } from 'react'

// ✅ 推荐:懒加载重量级组件
const HeavyChart = lazy(() => import('./HeavyChart'))

export function Dashboard() {
  return (
    <Suspense fallback={<Spinner />}>
      <HeavyChart />
    </Suspense>
  )
}
数据库查询
typescript
// ✅ 推荐:只查询必要的列
const { data } = await supabase
  .from('markets')
  .select('id, name, status')
  .limit(10)

// ❌ 不推荐:查询所有列
const { data } = await supabase
  .from('markets')
  .select('*')

测试标准

测试结构 (AAA 模式)
typescript
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)
})
测试命名
typescript
// ✅ 推荐:描述性测试名称
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', () => { })

// ❌ 不推荐:模糊的测试名称
test('works', () => { })
test('test search', () => { })

代码异味(Code Smell)检测

注意以下反模式:

1. 过长函数
typescript
// ❌ 不推荐:函数超过 50 行
function processMarketData() {
  // 100 行代码
}

// ✅ 推荐:拆分为更小的函数
function processMarketData() {
  const validated = validateData()
  const transformed = transformData(validated)
  return saveData(transformed)
}
2. 过深嵌套
typescript
// ❌ 不推荐:5 层以上的嵌套
if (user) {
  if (user.isAdmin) {
    if (market) {
      if (market.isActive) {
        if (hasPermission) {
          // 执行某些操作
        }
      }
    }
  }
}

// ✅ 推荐:卫语句 (Early Returns)
if (!user) return
if (!user.isAdmin) return
if (!market) return
if (!market.isActive) return
if (!hasPermission) return

// 执行某些操作
3. 魔术数字 (Magic Numbers)
typescript
// ❌ 不推荐:未解释的数字
if (retryCount > 3) { }
setTimeout(callback, 500)

// ✅ 推荐:具名常量
const MAX_RETRIES = 3
const DEBOUNCE_DELAY_MS = 500

if (retryCount > MAX_RETRIES) { }
setTimeout(callback, DEBOUNCE_DELAY_MS)

记住:代码质量是不容商量的。清晰、可维护的代码是快速开发和从容重构的基石。

© xu-xiang, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 1 other file in .agents/skills/coding-standards of xu-xiang/everything-claude-code-zh.

  • SKILL.md
  • agents/openai.yaml

Open the folder on GitHubat commit dfbf946

Compare with similar skills

Coding Standards next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Coding Standards compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Coding Standards this skillxu-xiang/everything-claude-code-zh2k—~2.4kAutomated safety check: PassMIT
Coding Standardskurealnum/dotfiles29017 repos~2.9kAutomated safety check: PassNone
Coding Standardsaffaan-m/ECC275k3 repos~2.6kAutomated safety check: PassMIT
Coding Standardsaffaan-m/ECC275k2 repos~2.6kAutomated safety check: PassMIT
Coding Standardsaffaan-m/ECC275k2 repos~2.7kAutomated safety check: PassMIT
Coding Standardsaffaan-m/ECC275k1 repos~3kAutomated safety check: PassMIT

Similar skills

  • Coding Standards

    kurealnum/dotfiles

    Universal coding standards, best practices, and patterns for TypeScript, JavaScript, React, and Node.js development.

    290 GitHub starsUsed in 17 repos~2.9k tokens
    DevelopmentAuto-check passed
  • Coding Standards

    affaan-m/ECC

    适用于TypeScript、JavaScript、React和Node.js开发的通用编码标准、最佳实践和模式. An agent skill from affaan-m/ECC.

    275k GitHub starsUsed in 3 repos~2.6k tokens
    DevelopmentAuto-check passed
  • Coding Standards

    affaan-m/ECC

    TypeScript、JavaScript、React、Node.js開発のための汎用コーディング標準、ベストプラクティス、パターン。

    275k GitHub starsUsed in 2 repos~2.6k tokens
    DevelopmentAuto-check passed
  • Coding Standards

    affaan-m/ECC

    TypeScript, JavaScript, React, Node.js 개발을 위한 범용 코딩 표준, 모범 사례 및 패턴.

    275k GitHub starsUsed in 2 repos~2.7k tokens
    DevelopmentAuto-check passed
  • Coding Standards

    affaan-m/ECC

    TypeScript, JavaScript, React ve Node.js geliştirme için evrensel kodlama standartları, en iyi uygulamalar ve kalıplar.

    275k GitHub starsUsed in 1 repo~3k tokens
    DevelopmentAuto-check passed
  • Coding Standards

    NeverSight/learn-skills.dev

    适用于 TypeScript、JavaScript、React 和 Node.js 开发的通用编码标准、最佳实践和模式。

    216 GitHub starsUsed in 1 repo~2.4k tokens
    DevelopmentAuto-check passed

More from xu-xiang/everything-claude-code-zh

All 78 skills in this repo
  • Configure Ecc

    xu-xiang/everything-claude-code-zh

    Everything Claude Code 的交互式安装程序 — 引导用户选择并安装技能和规则到用户级或项目级目录,验证路径,并可选择优化已安装文件。

    2k GitHub starsUsed in 1 repo~2.1k tokens
    Auto-check passed
  • Continuous Learning V2

    xu-xiang/everything-claude-code-zh

    基于本能(Instinct)的学习系统,通过钩子(hooks)观察会话,创建带有置信度评分的原子本能,并将其演化为技能(Skills)、命令(Commands)或智能体(Agents)。v2.1 版本增加了项目作用域(project-scoped)的本能,以防止跨项目污染。

    2k GitHub stars~2.1k tokensUpdated 7 mo ago
    Auto-check passed
  • API Design

    xu-xiang/everything-claude-code-zh

    生产级 API 的 REST API 设计模式,包括资源命名、状态码、分页、过滤、错误响应、版本控制和速率限制. An agent skill from xu-xiang/everything-claude-code-zh.

    2k GitHub stars~2.7k tokensUpdated 7 mo ago
    Auto-check passed
  • Backend Patterns

    xu-xiang/everything-claude-code-zh

    后端架构模式、API 设计、数据库优化以及适用于 Node.js、Express 和 Next.js API 路由的服务端最佳实践。

    2k GitHub stars~3.2k tokensUpdated 7 mo ago
    Auto-check passed
  • Backend Patterns

    xu-xiang/everything-claude-code-zh

    后端架构模式、API 设计、数据库优化以及 Node.js、Express 和 Next.js API 路由的服务端最佳实践。

    2k GitHub stars~3.1k tokensUpdated 7 mo ago
    Auto-check passed
  • Backend Patterns

    xu-xiang/everything-claude-code-zh

    后端架构模式、API 设计、数据库优化以及针对 Node.js、Express 和 Next.js API 路由的服务端最佳实践。

    2k GitHub stars~3.2k tokensUpdated 7 mo ago
    Auto-check passed

Categories

Questions about Coding Standards

What does Coding Standards do?

适用于 TypeScript、JavaScript、React 和 Node.js 开发的通用编码标准、最佳实践与模式。. Coding Standards is an agent skill from xu-xiang/everything-claude-code-zh.

When should I use Coding Standards?

Coding Standards fits situations like: tasks that involve Code quality.

How do I install Coding Standards in Claude Code?

Run `npx skills add xu-xiang/everything-claude-code-zh --skill coding-standards -a claude-code`. Or copy the skill folder (.agents/skills/coding-standards in xu-xiang/everything-claude-code-zh) into .claude/skills/coding-standards in your project. Claude Code loads it when a task matches its description.

How do I install Coding Standards in Codex?

Run `npx skills add xu-xiang/everything-claude-code-zh --skill coding-standards -a codex`. Or copy the skill folder (.agents/skills/coding-standards in xu-xiang/everything-claude-code-zh) into .agents/skills/coding-standards in your project. Codex loads it when a task matches its description.

Can I use Coding Standards in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add xu-xiang/everything-claude-code-zh --skill coding-standards -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/coding-standards, .gemini/skills/coding-standards, .github/skills/coding-standards and .opencode/skills/coding-standards in your project.

What does Coding Standards need to run?

SKILL.md names no scripts, command-line tools or credentials: Coding Standards is instructions for the agent only. Our summary lists: Node.js.

Does Coding Standards access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Coding Standards safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Coding Standards use?

Coding Standards is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Coding Standards use?

About 2.4k tokens (SKILL.md is roughly 9.5k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Coding Standards?

Skills that share tags, products or a category with Coding Standards: Coding Standards (kurealnum/dotfiles, 290 stars), Coding Standards (affaan-m/ECC, 275k stars), Coding Standards (affaan-m/ECC, 275k stars) and Coding Standards (affaan-m/ECC, 275k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Coding Standards?

xu-xiang (a GitHub user) maintains it in xu-xiang/everything-claude-code-zh, which has 1,973 GitHub stars. The repository holds 78 skills in this directory. The repository was last updated on March 5, 2026.

Source: xu-xiang/everything-claude-code-zh on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.