以下是現代前端項目的完整代碼規范配置方案,涵蓋主流技術棧和自動化工具鏈配置:
一、基礎工程配置
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"'
七、最佳實踐總結
-
命名規范:
- PascalCase:Vue組件、TypeScript 類型
- camelCase:JavaScript 變量/函數
- kebab-case:CSS類名、文件名
-
代碼組織:
- 組件復雜度控制:單個組件不超過 500 行
- 方法長度限制:單個方法不超過 50 行
- 文件大小限制:單文件不超過 1000 行
-
性能優化:
// 組件懶加載 const UserProfile = () => import('./UserProfile.vue')// 圖片懶加載 <img v-lazy="imageUrl" />
-
文檔規范:
/*** 格式化日期* @param {Date} date - 需要格式化的日期對象* @param {string} format - 格式字符串* @returns {string} 格式化后的日期字符串*/ function formatDate(date, format = 'YYYY-MM-DD') {// ... }
該配置方案適用于 Vue3 + TypeScript + Vite 技術棧,可根據項目需求調整擴展規則。建議搭配 VSCode 的 ESLint、Prettier 插件實現實時校驗。