DEVELOPMENT.md 3.7 KB

开发规范 (Development Guidelines)

Import 语句规范

❌ 禁止使用文件扩展名

错误示例:

// ❌ 不要这样写
import { CredentialManager } from './credential-manager/CredentialManager.js'
import { Platform } from '../types/credential.ts'
import utils from './utils/helper.js'

正确示例:

// ✅ 正确写法
import { CredentialManager } from './credential-manager/CredentialManager'
import { Platform } from '../types/credential'
import utils from './utils/helper'

📁 推荐的 Import 模式

1. 使用路径别名(Path Aliases)

// ✅ 推荐:使用配置的路径别名
import { CredentialManager } from '@/core/credential-manager'
import { Platform } from '@/types/credential'
import { logger } from '@/utils/logger'

2. Import 顺序规范

// 1. Node.js 内置模块
import { readFile } from 'fs'
import { join } from 'path'

// 2. 第三方 npm 包
import { describe, test, expect } from '@jest/globals'
import axios from 'axios'

// 3. 内部模块(@/ 开头)
import { CredentialManager } from '@/core/credential-manager'
import { Platform } from '@/types/credential'

// 4. 相对路径导入
import { helper } from '../utils/helper'
import { config } from './config'

ESLint 自动检查

项目已配置 ESLint 规则自动检查 import 语句:

启用的规则:

  • import/extensions: 禁止使用文件扩展名
  • import/no-unresolved: 确保导入路径存在
  • import/no-duplicates: 禁止重复导入
  • import/order: 自动排序导入语句

运行检查:

# 检查所有文件
npm run lint

# 自动修复可修复的问题
npm run lint:fix

# 检查特定文件
npx eslint src/path/to/file.ts

IDE 配置建议

VS Code 配置

.vscode/settings.json 中添加:

{
  "typescript.suggest.includeCompletionsForModuleExports": true,
  "typescript.suggest.includeCompletionsWithInsertText": true,
  "typescript.preferences.includePackageJsonAutoImports": "auto",
  "typescript.suggest.autoImports": true,

  // 自动移除文件扩展名
  "typescript.suggest.paths": false,

  // ESLint 自动修复
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true,
    "source.organizeImports": true
  },

  // 保存时自动格式化
  "editor.formatOnSave": true
}

WebStorm/IntelliJ 配置

  1. 进入 Settings > Editor > Code Style > TypeScript > Imports
  2. 设置 Use relative imports for files in the same directory: false
  3. 设置 Import with file extension: Never
  4. 启用 ESLint 集成:Settings > Languages > JavaScript > Code Quality Tools > ESLint

常见问题解决

Q: 为什么要禁止文件扩展名?

A:

  1. 兼容性:TypeScript 编译后的输出可能改变文件扩展名
  2. 一致性:保持代码风格统一
  3. 重构友好:文件重命名时不需要更新所有引用
  4. 构建优化:打包工具能更好地处理模块解析

Q: ESLint 报错 "Unable to resolve path to module"

A:

  1. 确保 tsconfig.json 中的 paths 配置正确
  2. 检查文件是否存在
  3. 运行 npm install 确保依赖安装完整

Q: 自动导入还是带扩展名怎么办?

A:

  1. 更新 IDE 设置(参考上面的配置)
  2. 使用 npm run lint:fix 自动修复
  3. 手动移除扩展名

团队协作

代码审查清单

  • 所有 import 语句都没有文件扩展名
  • 使用了路径别名(@/)而不是深层相对路径
  • Import 语句按规范排序
  • ESLint 检查通过

Git Hook 建议

# 在 .husky/pre-commit 中添加
npm run lint

记住:一致的 import 风格让代码更易读、易维护!🚀