当前位置: 首页 > backend >正文

前端代码规范详细配置

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


一、基础工程配置

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 插件实现实时校验。

http://www.xdnf.cn/news/4578.html

相关文章:

  • CSS手动布局
  • 60页PDF | 四川电信数据湖 + 数据中台实施方案:覆盖数据能力、数据资产及数据治理的全流程建设指南
  • 从xjtu-sy数据集中看轴承故障的发展趋势与基本特征
  • 南京大学OpenHarmony技术俱乐部正式揭牌 仓颉编程语言引领生态创新
  • 5. HTML 转义字符:在网页中正确显示特殊符号
  • Linux系列:如何用perf跟踪.NET程序的mmap泄露
  • 水印落幕 7.0 | 专门用于去除图片和视频中水印的工具,支持自定义水印添加
  • 【测试开发】BUG篇 - 从理解BUG到如何处理
  • 递归element-ui el-menu 实现无限级子菜单
  • Spring 项目无法连接 MySQL:Nacos 配置误区排查与解决
  • AI——认知建模工具:ACT-R
  • #黑马点评#(二)商户查询缓存
  • 新疆地区主要灾害链总结
  • 网络编程(一)
  • seamless_communication,facebook推出的开源语音翻译项目
  • 代码随想录算法训练营 Day39 动态规划Ⅶ 打家劫舍
  • 数据可视化:php+echarts实现数据可视化(包含echart安装引入)
  • 数据压缩实现案例
  • 以pytest_addoption 为例,讲解pytest框架中钩子函数的应用
  • RAG技术体系问题的系统性总结
  • C++并发编程完全指南:从基础到实践
  • BBDM学习笔记
  • Spring Boot 中 AOP 的自动装配原理
  • C语言复习笔记--自定义类型
  • Nacos源码—5.Nacos配置中心实现分析二
  • QT高级(1)QTableView自定义委托集合,一个类实现若干委托
  • C——函数递归
  • 软考冲刺——OSPF简答题
  • 仿真系统-学生选课管理
  • 数字化转型是往哪转?怎么转?