file-organizer

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

File Organizer

文件组织指南

Overview

概述

Design and maintain well-organized project structures that scale with team and codebase growth. This skill covers monorepo patterns, feature-based vs layer-based architecture, naming conventions, index/barrel files, configuration file placement, and documentation structure.
Apply this skill whenever a project's file organization needs to be established, audited, or restructured for clarity and scalability.
设计并维护可随团队和代码库增长扩展的高组织性项目结构。本技能涵盖monorepo模式、基于特性vs基于层级的架构、命名规范、index/barrel文件、配置文件放置以及文档结构。
当需要新建、审计或重构项目的文件组织以提升清晰度和可扩展性时,即可应用本技能。

Multi-Phase Process

多阶段流程

Phase 1: Assessment

阶段1:评估

  1. Audit current project structure and identify pain points
  2. Measure project size (file count, team size, feature count)
  3. Identify existing naming conventions and import patterns
  4. Catalog configuration file locations
  5. Check for circular dependencies or deep nesting
STOP — Do NOT propose a new structure without understanding the current state and its pain points.
  1. 审计当前项目结构,识别痛点
  2. 评估项目规模(文件数量、团队规模、特性数量)
  3. 识别现有命名规范和导入模式
  4. 整理配置文件位置目录
  5. 检查循环依赖或过深的嵌套层级
注意——未了解当前状态及其痛点之前,请勿提出新的结构方案。

Phase 2: Strategy Selection

阶段2:策略选择

  1. Choose organization strategy using decision table below
  2. Define naming conventions and file placement rules
  3. Plan barrel export boundaries
  4. Establish configuration file placement rules
  5. Document import ordering convention
STOP — Do NOT begin migration without documenting the target structure and getting team alignment.
  1. 使用下方的决策表选择组织策略
  2. 定义命名规范和文件放置规则
  3. 规划barrel export的边界
  4. 制定配置文件放置规则
  5. 文档化导入排序规范
注意——未文档化目标结构并获得团队一致认可之前,请勿开始迁移。

Phase 3: Migration Planning

阶段3:迁移规划

  1. Plan migration path for existing projects (incremental, not big-bang)
  2. Identify files that move and their new locations
  3. Map import changes required
  4. Create automated codemods where possible
  5. Define rollback plan if migration causes issues
STOP — Do NOT execute migration without verifying tests pass at each incremental step.
  1. 为现有项目规划迁移路径(采用增量式而非一次性迁移)
  2. 确定需要移动的文件及其新位置
  3. 映射所需的导入路径变更
  4. 尽可能创建自动化codemods
  5. 定义迁移出现问题时的回滚方案
注意——未在每一个增量步骤验证测试通过之前,请勿执行迁移。

Phase 4: Execution and Validation

阶段4:执行与验证

  1. Move one feature or module at a time
  2. Update imports using automated tools
  3. Verify tests pass after each move
  4. Remove old structure after complete migration
  5. Document conventions for team reference
  1. 每次仅移动一个特性或模块
  2. 使用自动化工具更新导入路径
  3. 每次移动后验证测试全部通过
  4. 完整迁移完成后删除旧结构
  5. 文档化规范供团队参考

Architecture Strategy Decision Table

架构策略决策表

Project SizeTeam SizeRecommendationWhy
< 20 files1-2 devsLayer-basedSimple, low overhead
20-100 files2-5 devsHybridBalance of simplicity and scalability
100+ files5+ devsFeature-basedSelf-contained modules reduce conflicts
Multiple apps sharing codeAnyMonorepoShared packages with clear boundaries
Rapid prototype / MVP1-3 devsLayer-basedSpeed over structure, refactor later
Enterprise, multiple teams10+ devsFeature-based + MonorepoTeam ownership per feature module
项目规模团队规模推荐方案原因
< 20个文件1-2名开发者基于层级的架构简单,开销低
20-100个文件2-5名开发者混合架构平衡简单性和可扩展性
100+个文件5+名开发者基于特性的架构自包含模块减少冲突
多个应用共享代码任意规模Monorepo边界清晰的共享包
快速原型 / MVP1-3名开发者基于层级的架构速度优先于结构,后续再重构
企业级,多团队协作10+名开发者基于特性的架构 + Monorepo每个特性模块由对应团队负责

Architecture Patterns

架构模式

Feature-Based (Domain-Driven)

基于特性(领域驱动)

Organize by business domain. Each feature is self-contained.
src/
  features/
    auth/
      components/
        LoginForm.tsx
        SignupForm.tsx
      hooks/
        useAuth.ts
      api/
        auth.api.ts
      types/
        auth.types.ts
      utils/
        auth.utils.ts
      __tests__/
        auth.test.ts
      index.ts          # Public API (barrel export)
    dashboard/
      components/
      hooks/
      api/
      types/
      index.ts
    billing/
      ...
  shared/               # Cross-feature shared code
    components/
      Button.tsx
      Modal.tsx
    hooks/
      useDebounce.ts
    utils/
      format.ts
    types/
      common.types.ts
Best for: Teams > 5 developers, medium-large applications, clear domain boundaries.
按业务领域组织,每个特性都是自包含的。
src/
  features/
    auth/
      components/
        LoginForm.tsx
        SignupForm.tsx
      hooks/
        useAuth.ts
      api/
        auth.api.ts
      types/
        auth.types.ts
      utils/
        auth.utils.ts
      __tests__/
        auth.test.ts
      index.ts          # Public API (barrel export)
    dashboard/
      components/
      hooks/
      api/
      types/
      index.ts
    billing/
      ...
  shared/               # Cross-feature shared code
    components/
      Button.tsx
      Modal.tsx
    hooks/
      useDebounce.ts
    utils/
      format.ts
    types/
      common.types.ts
最佳适用场景:团队规模>5名开发者、中大型应用、领域边界清晰。

Layer-Based (Technical)

基于层级(技术维度)

Organize by technical concern.
src/
  components/
    Button.tsx
    Modal.tsx
    LoginForm.tsx
    DashboardCard.tsx
  hooks/
    useAuth.ts
    useDebounce.ts
  services/
    auth.service.ts
    billing.service.ts
  utils/
    format.ts
    validation.ts
  types/
    auth.types.ts
    billing.types.ts
  pages/
    Home.tsx
    Dashboard.tsx
Best for: Small teams (1-3), simple applications, rapid prototyping.
按技术关注点组织。
src/
  components/
    Button.tsx
    Modal.tsx
    LoginForm.tsx
    DashboardCard.tsx
  hooks/
    useAuth.ts
    useDebounce.ts
  services/
    auth.service.ts
    billing.service.ts
  utils/
    format.ts
    validation.ts
  types/
    auth.types.ts
    billing.types.ts
  pages/
    Home.tsx
    Dashboard.tsx
最佳适用场景:小型团队(1-3人)、简单应用、快速原型开发。

Hybrid (Recommended Default)

混合架构(推荐默认方案)

Combine both: shared layer + feature modules.
src/
  app/                  # App-level concerns
    layout.tsx
    providers.tsx
    routes.tsx
  features/             # Feature modules
    auth/
    dashboard/
    billing/
  components/           # Shared UI components
    ui/                 # Design system atoms
    layout/             # Layout components
  hooks/                # Shared hooks
  lib/                  # Shared utilities
  types/                # Shared types
  config/               # App configuration
  styles/               # Global styles
结合两者优势:共享层 + 特性模块。
src/
  app/                  # App-level concerns
    layout.tsx
    providers.tsx
    routes.tsx
  features/             # Feature modules
    auth/
    dashboard/
    billing/
  components/           # Shared UI components
    ui/                 # Design system atoms
    layout/             # Layout components
  hooks/                # Shared hooks
  lib/                  # Shared utilities
  types/                # Shared types
  config/               # App configuration
  styles/               # Global styles

Monorepo Patterns

Monorepo模式

Turborepo / pnpm Workspaces

Turborepo / pnpm Workspaces

root/
  apps/
    web/                # Next.js web app
      package.json
    api/                # API server
      package.json
    mobile/             # React Native app
      package.json
  packages/
    ui/                 # Shared component library
      package.json
    config/             # Shared configs (ESLint, TypeScript)
      eslint/
      typescript/
      package.json
    utils/              # Shared utilities
      package.json
    types/              # Shared type definitions
      package.json
  package.json          # Root workspace config
  turbo.json            # Turborepo pipeline config
  pnpm-workspace.yaml
root/
  apps/
    web/                # Next.js web app
      package.json
    api/                # API server
      package.json
    mobile/             # React Native app
      package.json
  packages/
    ui/                 # Shared component library
      package.json
    config/             # Shared configs (ESLint, TypeScript)
      eslint/
      typescript/
      package.json
    utils/              # Shared utilities
      package.json
    types/              # Shared type definitions
      package.json
  package.json          # Root workspace config
  turbo.json            # Turborepo pipeline config
  pnpm-workspace.yaml

Package Boundaries

包边界

  • Apps depend on packages, never on other apps
  • Packages can depend on other packages
  • No circular dependencies
  • Each package has a clear, single responsibility
  • Shared packages export via
    index.ts
    barrel
  • 应用依赖包,永远不依赖其他应用
  • 包可以依赖其他包
  • 不允许循环依赖
  • 每个包都有清晰单一的职责
  • 共享包通过
    index.ts
    barrel导出

Configuration Sharing

配置共享

json
// packages/config/typescript/base.json
{
  "compilerOptions": {
    "strict": true,
    "moduleResolution": "bundler",
    "target": "ES2022"
  }
}

// apps/web/tsconfig.json
{
  "extends": "@repo/config/typescript/nextjs",
  "include": ["src"]
}
json
// packages/config/typescript/base.json
{
  "compilerOptions": {
    "strict": true,
    "moduleResolution": "bundler",
    "target": "ES2022"
  }
}

// apps/web/tsconfig.json
{
  "extends": "@repo/config/typescript/nextjs",
  "include": ["src"]
}

Naming Conventions

命名规范

Files and Directories

文件和目录

TypeConventionExample
ComponentsPascalCase
UserProfile.tsx
HookscamelCase with
use
prefix
useAuth.ts
UtilitiescamelCase
formatDate.ts
TypescamelCase with
.types
suffix
auth.types.ts
Testssame name with
.test
suffix
UserProfile.test.tsx
Stylessame name with
.module.css
suffix
UserProfile.module.css
ConstantscamelCase or UPPER_SNAKE in file
config.ts
API/ServicescamelCase with
.api
or
.service
auth.api.ts
Directorieskebab-case
user-profile/
类型规范示例
组件PascalCase
UserProfile.tsx
Hooks小驼峰,带
use
前缀
useAuth.ts
工具函数小驼峰
formatDate.ts
类型定义小驼峰,带
.types
后缀
auth.types.ts
测试文件和对应文件同名,带
.test
后缀
UserProfile.test.tsx
样式文件和对应文件同名,带
.module.css
后缀
UserProfile.module.css
常量小驼峰或大写下划线命名
config.ts
API/服务文件小驼峰,带
.api
.service
后缀
auth.api.ts
目录kebab-case
user-profile/

Component File Naming

组件文件命名

undefined
undefined

Single-file component

Single-file component

Button.tsx
Button.tsx

Component with co-located files

Component with co-located files

Button/ Button.tsx Button.test.tsx Button.stories.tsx Button.module.css index.ts # Re-exports Button
undefined
Button/ Button.tsx Button.test.tsx Button.stories.tsx Button.module.css index.ts # Re-exports Button
undefined

Import Ordering Convention

导入排序规范

typescript
// 1. External packages
import React from 'react';
import { useQuery } from '@tanstack/react-query';

// 2. Internal packages (monorepo)
import { Button } from '@repo/ui';

// 3. Feature-level imports
import { useAuth } from '@/features/auth';

// 4. Relative imports (same feature)
import { LoginForm } from './LoginForm';
import { authSchema } from './auth.types';

// 5. Styles
import styles from './Auth.module.css';
typescript
// 1. External packages
import React from 'react';
import { useQuery } from '@tanstack/react-query';

// 2. Internal packages (monorepo)
import { Button } from '@repo/ui';

// 3. Feature-level imports
import { useAuth } from '@/features/auth';

// 4. Relative imports (same feature)
import { LoginForm } from './LoginForm';
import { authSchema } from './auth.types';

// 5. Styles
import styles from './Auth.module.css';

Index Files and Barrel Exports

Index文件与Barrel Exports

Barrel Export Pattern

Barrel Export模式

typescript
// features/auth/index.ts — Public API
export { LoginForm } from './components/LoginForm';
export { useAuth } from './hooks/useAuth';
export type { User, AuthState } from './types/auth.types';

// Do NOT export internal implementation details
// Do NOT export utility functions used only within the feature
typescript
// features/auth/index.ts — Public API
export { LoginForm } from './components/LoginForm';
export { useAuth } from './hooks/useAuth';
export type { User, AuthState } from './types/auth.types';

// Do NOT export internal implementation details
// Do NOT export utility functions used only within the feature

Barrel Export Decision Table

Barrel Export决策表

ContextUse Barrel?Why
Feature module public APIYes, alwaysClean boundary, controlled surface area
Shared component libraryYes, alwaysSingle import point for consumers
Utility librariesYes, alwaysDiscoverability for shared functions
Inside a feature (internal)NoImport directly, avoid indirection
Would cause circular dependenciesNoBreak the cycle, import directly
Hurts tree-shaking (verified)NoUse direct imports for bundle size
场景是否使用Barrel?原因
特性模块公共API是,始终使用边界清晰,控制暴露面
共享组件库是,始终使用为使用者提供单一导入入口
工具库是,始终使用提升共享函数的可发现性
特性内部使用直接导入,避免间接跳转
会导致循环依赖打破循环,直接导入
已验证会影响tree-shaking使用直接导入控制包体积

Configuration File Placement

配置文件放置

Root-Level Configuration

根层级配置

root/
  .editorconfig         # Editor settings
  .eslintrc.js          # ESLint config (or eslint.config.js)
  .gitignore            # Git ignore rules
  .prettierrc           # Prettier config
  .env.example          # Environment variable template
  docker-compose.yml    # Docker composition
  Dockerfile            # Container build
  package.json          # Dependencies and scripts
  tsconfig.json         # TypeScript config
  next.config.js        # Framework config
  tailwind.config.ts    # Tailwind config
  vitest.config.ts      # Test config
root/
  .editorconfig         # Editor settings
  .eslintrc.js          # ESLint config (or eslint.config.js)
  .gitignore            # Git ignore rules
  .prettierrc           # Prettier config
  .env.example          # Environment variable template
  docker-compose.yml    # Docker composition
  Dockerfile            # Container build
  package.json          # Dependencies and scripts
  tsconfig.json         # TypeScript config
  next.config.js        # Framework config
  tailwind.config.ts    # Tailwind config
  vitest.config.ts      # Test config

Environment Files

环境变量文件

.env                    # Local defaults (gitignored)
.env.example            # Template with dummy values (committed)
.env.local              # Local overrides (gitignored)
.env.development        # Development-specific (committed or not)
.env.production         # Production-specific (committed or not)
.env.test               # Test-specific (committed or not)
.env                    # Local defaults (gitignored)
.env.example            # Template with dummy values (committed)
.env.local              # Local overrides (gitignored)
.env.development        # Development-specific (committed or not)
.env.production         # Production-specific (committed or not)
.env.test               # Test-specific (committed or not)

Documentation Structure

文档结构

docs/
  architecture/
    adr/                # Architecture Decision Records
      001-framework.md
      002-database.md
    diagrams/
  api/                  # API documentation
  guides/
    getting-started.md
    deployment.md
  contributing.md
docs/
  architecture/
    adr/                # Architecture Decision Records
      001-framework.md
      002-database.md
    diagrams/
  api/                  # API documentation
  guides/
    getting-started.md
    deployment.md
  contributing.md

Migration Strategy

迁移策略

Incremental Migration (Recommended)

增量迁移(推荐)

  1. Create the target structure alongside existing code
  2. Move one feature/module at a time
  3. Update imports using automated codemods
  4. Verify with tests after each move
  5. Remove old structure after complete migration
  1. 在现有代码旁创建目标结构
  2. 每次仅移动一个特性/模块
  3. 使用自动化codemods更新导入路径
  4. 每次移动后通过测试验证
  5. 完整迁移完成后删除旧结构

Automated Tools

自动化工具

  • ts-morph
    : programmatic TypeScript refactoring
  • jscodeshift
    : JavaScript codemods
  • IDE refactoring: rename/move with automatic import updates
  • ESLint
    import/order
    : enforce import ordering
  • ts-morph
    : 程序化TypeScript重构
  • jscodeshift
    : JavaScript codemods工具
  • IDE重构:重命名/移动文件时自动更新导入路径
  • ESLint
    import/order
    : 强制导入排序规则

Anti-Patterns / Common Mistakes

反模式/常见错误

Anti-PatternWhy It FailsWhat To Do Instead
Deeply nested folders (> 4 levels)Hard to navigate, long import pathsFlatten structure, use path aliases
utils/
as a dumping ground
Becomes unmaintainable junk drawerOrganize utils by domain or purpose
Circular dependencies between featuresBuild failures, unclear ownershipFeatures import only from shared or own modules
Barrel exports re-exporting everythingKills tree-shaking, bloats bundlesExport only the public API
Inconsistent naming (mixed conventions)Cognitive load, merge conflictsPick one convention, enforce with linter
Config scattered across multiple locationsHard to find and maintainAll config at project root
Tests in separate directory treeHard to find tests for a fileCo-locate tests with source code
100+ files in one flat folderImpossible to navigateGroup into sub-modules or features
Index files containing logicUnexpected side effects on importIndex files only re-export
Big-bang migration (move everything at once)High risk, hard to rollbackIncremental moves with tests after each
反模式失败原因替代方案
文件夹嵌套过深(>4层)难以导航,导入路径过长扁平化结构,使用路径别名
utils/
沦为垃圾场
变成难以维护的杂物抽屉按领域或用途组织工具函数
特性之间存在循环依赖构建失败,所有权不清晰特性仅从共享模块或自身模块导入
Barrel export导出所有内容破坏tree-shaking,增大包体积仅导出公共API
命名不一致(混合规范)增加认知负担,容易出现合并冲突选择一套规范,通过linter强制执行
配置散落在多个位置难以查找和维护所有配置放置在项目根目录
测试文件放在独立的目录树中难以找到对应文件的测试测试文件与源代码同位置放置
单个扁平文件夹下有100+个文件完全无法导航拆分为子模块或特性分组
Index文件包含业务逻辑导入时出现意外副作用Index文件仅用于重新导出
一次性大爆炸式迁移风险高,难以回滚增量移动,每次移动后进行测试验证

Anti-Rationalization Guards

不合理行为规避规则

  • Do NOT restructure without understanding current pain points -- assess first.
  • Do NOT skip the team alignment step -- structure changes affect everyone.
  • Do NOT migrate everything at once -- move one module at a time with test verification.
  • Do NOT create deeply nested structures "for future scalability" -- flatten until complexity demands it.
  • Do NOT ignore barrel export impact on bundle size -- verify with bundle analyzer.
  • 未了解当前痛点请勿重构——先做评估。
  • 请勿跳过团队对齐步骤——结构变更影响所有人。
  • 请勿一次性迁移所有内容——每次移动一个模块并做测试验证。
  • 请勿为了"未来可扩展性"创建过深的嵌套结构——保持扁平,直到复杂度确实需要分层。
  • 请勿忽略barrel export对包体积的影响——使用包体积分析工具验证。

Integration Points

关联技能

SkillHow It Connects
senior-frontend
Frontend project structure follows feature-based or hybrid patterns
senior-architect
Architecture decisions inform module boundaries and package structure
senior-fullstack
Full-stack projects need coordinated frontend/backend organization
clean-code
Naming conventions and module boundaries support clean code principles
deployment
Monorepo structure affects CI/CD pipeline configuration
laravel-specialist
Laravel projects follow framework-specific directory conventions
技能关联方式
senior-frontend
前端项目结构遵循基于特性或混合模式
senior-architect
架构决策决定模块边界和包结构
senior-fullstack
全栈项目需要协调前端/后端的组织方式
clean-code
命名规范和模块边界符合干净代码原则
deployment
Monorepo结构影响CI/CD流水线配置
laravel-specialist
Laravel项目遵循框架特定的目录规范

Skill Type

技能类型

FLEXIBLE — Choose the organization strategy that fits the project's size, team structure, and complexity. The naming conventions and barrel export patterns are recommendations that should be adapted to existing project conventions.
灵活适配——选择符合项目规模、团队结构和复杂度的组织策略。命名规范和barrel export模式为推荐方案,可根据现有项目规范调整。