前端代码规范详细配置

发布于:2025-05-13 ⋅ 阅读:(86) ⋅ 点赞:(0)

以下是现代前端项目的完整代码规范配置方案,涵盖主流技术栈和自动化工具链配置:


一、基础工程配置

1. 项目结构规范
project/
├── src/
│   ├── assets/         # 静态资源
│   ├── components/     # 通用组件
│   ├── layouts/        # 布局组件
│   ├── router/         # 路由配置
│   ├── store/          # 状态管理
│   ├── styles/         # 全局样式
│   ├── utils/          # 工具函数
│   └── views/          # 页面组件
├── .editorconfig       # 编辑器统一配置
├── .eslintrc.js        # ESLint 配置
├── .prettierrc         # Prettier 配置
├── .stylelintrc.js     # Stylelint 配置
└── .commitlintrc.js    # Git 提交规范

二、JavaScript/TypeScript 规范

1. ESLint 配置 (.eslintrc.js)
module.exports = {
  root: true,
  env: { browser: true, es2021: true },
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:vue/vue3-recommended', // Vue项目添加
    'prettier'
  ],
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module'
  },
  rules: {
    // 核心规则
    'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    'max-depth': ['error', 4], // 最大嵌套层级
    
    // TypeScript 规则
    '@typescript-eslint/no-explicit-any': 'off',
    '@typescript-eslint/ban-ts-comment': 'warn',
    
    // Vue 专用规则
    'vue/multi-word-component-names': 'off',
    'vue/html-self-closing': ['error', {
      html: { void: 'always' }
    }]
  },
  overrides: [
    {
      files: ['*.vue'],
      rules: {
        'max-lines-per-function': 'off'
      }
    }
  ]
};
2. Prettier 配置 (.prettierrc)
{
  "printWidth": 100,
  "tabWidth": 2,
  "useTabs": false,
  "semi": true,
  "singleQuote": true,
  "quoteProps": "consistent",
  "trailingComma": "none",
  "bracketSpacing": true,
  "arrowParens": "avoid",
  "vueIndentScriptAndStyle": true,
  "htmlWhitespaceSensitivity": "ignore"
}

三、CSS/SCSS 规范

1. Stylelint 配置 (.stylelintrc.js)
module.exports = {
  extends: [
    'stylelint-config-standard',
    'stylelint-config-recommended-scss',
    'stylelint-config-prettier'
  ],
  plugins: ['stylelint-order'],
  rules: {
    'selector-class-pattern': '^[a-z][a-z0-9]*(-[a-z0-9]+)*$', // 短横线命名
    'order/properties-order': [
      'position',
      'top',
      'display',
      'flex-direction', // 按逻辑分组排序
      'width',
      'height',
      'margin',
      'padding',
      'color',
      'background'
    ],
    'max-nesting-depth': 3, // 最大嵌套层级
    'scss/at-import-partial-extension': 'never'
  }
};
2. BEM 命名示例
// Good
.user-profile {
  &__avatar { ... }
  &__name--highlight { ... }
}

// Bad
.userProfile {
  .avatar { ... }
  .nameHighlight { ... }
}

四、Vue 组件规范

1. 单文件组件结构
<template>
  <!-- 组件根元素使用 kebab-case -->
  <div class="user-card">
    <!-- 使用 PascalCase 组件名 -->
    <UserAvatar />
  </div>
</template>

<script setup>
// 组合式 API 规范
import { ref } from 'vue'

// 变量命名
const isLoading = ref(false)

// 方法命名
const handleButtonClick = () => { ... }
</script>

<style lang="scss" scoped>
.user-card {
  // Scoped 样式
}
</style>
2. Props 定义规范
// TypeScript 类型定义
interface Props {
  /** 用户ID */
  userId: number
  /** 是否显示详情 */
  showDetail?: boolean
}

const props = defineProps<Props>()

五、Git 提交规范

1. Commitlint 配置 (.commitlintrc.js)
module.exports = {
  extends: ['@commitlint/config-conventional'],
  rules: {
    'type-enum': [
      2,
      'always',
      ['feat', 'fix', 'docs', 'style', 'refactor', 'perf', 'test', 'build', 'ci', 'chore', 'revert']
    ],
    'subject-case': [0]
  }
};
2. Commitizen 适配器
# 安装工具
npm install -g commitizen cz-conventional-changelog

# 提交示例
git commit -m "feat(user): add login functionality"

六、自动化工具链

1. Husky + lint-staged 配置
// package.json
{
  "scripts": {
    "prepare": "husky install",
    "lint": "npm run lint:js && npm run lint:style",
    "lint:js": "eslint --ext .js,.vue src",
    "lint:style": "stylelint src/**/*.{css,scss,vue}"
  },
  "lint-staged": {
    "*.{js,vue}": ["eslint --fix", "prettier --write"],
    "*.{css,scss}": ["stylelint --fix", "prettier --write"]
  }
}
2. Git Hook 配置
# 创建 pre-commit hook
npx husky add .husky/pre-commit "npx lint-staged"

# 创建 commit-msg hook
npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'

七、最佳实践总结

  1. 命名规范

    • PascalCase:Vue组件、TypeScript 类型
    • camelCase:JavaScript 变量/函数
    • kebab-case:CSS类名、文件名
  2. 代码组织

    • 组件复杂度控制:单个组件不超过 500 行
    • 方法长度限制:单个方法不超过 50 行
    • 文件大小限制:单文件不超过 1000 行
  3. 性能优化

    // 组件懒加载
    const UserProfile = () => import('./UserProfile.vue')
    
    // 图片懒加载
    <img v-lazy="imageUrl" />
    
  4. 文档规范

    /**
     * 格式化日期
     * @param {Date} date - 需要格式化的日期对象
     * @param {string} format - 格式字符串
     * @returns {string} 格式化后的日期字符串
     */
    function formatDate(date, format = 'YYYY-MM-DD') {
      // ...
    }
    

该配置方案适用于 Vue3 + TypeScript + Vite 技术栈,可根据项目需求调整扩展规则。建议搭配 VSCode 的 ESLint、Prettier 插件实现实时校验。