Code style unification solution
The Necessity of Team Collaboration Standards
In team collaborative development, inconsistent code styles can lead to increased maintenance costs, reduced code readability, and other issues. Different developers using varying indentation styles, naming conventions, or code organization patterns can make a project increasingly difficult to maintain. A unified code style standard can significantly improve team collaboration efficiency and reduce the onboarding cost for new members.
Code Formatting Tool Configuration
Prettier is currently the most popular code formatting tool, supporting multiple languages. Install and configure it in your project:
npm install --save-dev prettier
Create a .prettierrc
configuration file:
{
"printWidth": 100,
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": true,
"trailingComma": "es5",
"bracketSpacing": true,
"arrowParens": "always"
}
Install the Prettier plugin in VS Code and enable the "Format On Save" option to automatically format your code.
ESLint Rule Customization
ESLint is used to check code quality issues. When used with Prettier, install eslint-config-prettier
to avoid rule conflicts:
npm install eslint eslint-config-prettier --save-dev
Example .eslintrc.js
configuration:
module.exports = {
extends: ['eslint:recommended', 'plugin:react/recommended', 'prettier'],
rules: {
'no-console': 'warn',
'react/prop-types': 'off',
'no-unused-vars': ['error', { argsIgnorePattern: '^_' }]
}
};
Unified Naming Conventions
Variable Naming
- Use camelCase for variables and functions
- Constants use UPPER_SNAKE_CASE
- Boolean variables start with is/has/should
// Good
const MAX_COUNT = 100;
let currentUser = {};
function getUserInfo() {}
const isLoading = true;
// Bad
const maxcount = 100;
let CurrentUser = {};
function get_user_info() {}
const loading = true;
Component Naming
React components use PascalCase, with filenames matching the component name:
// UserProfile.jsx
function UserProfile() {
return <div>...</div>;
}
Code Organization Structure
File Structure Standards
Organize files by feature rather than by type:
src/
features/
user/
components/
hooks/
utils/
index.js
shared/
components/
styles/
constants/
Component Code Order
Organize code inside React components in the following order:
import React from 'react';
import PropTypes from 'prop-types';
const MyComponent = ({ prop1, prop2 }) => {
// 1. State hooks
const [state, setState] = useState();
// 2. Effect hooks
useEffect(() => {}, []);
// 3. Handler functions
const handleClick = () => {};
// 4. Render content
return <div onClick={handleClick}>{prop1}</div>;
};
MyComponent.propTypes = {
prop1: PropTypes.string.isRequired,
prop2: PropTypes.number
};
export default MyComponent;
Pre-Commit Checks
Use husky and lint-staged to automatically check code before committing:
npm install husky lint-staged --save-dev
package.json
configuration:
{
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{js,jsx,ts,tsx}": ["eslint --fix", "prettier --write"],
"*.{json,md}": ["prettier --write"]
}
}
Commenting Standards
Component Comments
Complex components should include file header comments explaining their purpose:
/**
* User information card component
* @param {Object} user - User data object
* @param {boolean} editable - Whether it's editable
* @param {Function} onSave - Save callback
*/
function UserCard({ user, editable, onSave }) {
// ...
}
Complex Logic Comments
Add detailed comments for complex algorithms or business logic:
// Use Floyd's cycle-finding algorithm to detect linked list cycles
function hasCycle(head) {
let slow = head;
let fast = head;
while (fast && fast.next) {
slow = slow.next;
fast = fast.next.next;
// If fast and slow pointers meet, a cycle exists
if (slow === fast) return true;
}
return false;
}
Style Writing Standards
CSS-in-JS Standards
When using styled-components, follow these guidelines:
const Button = styled.button`
padding: 0.5rem 1rem;
background: ${props => props.primary ? '#1890ff' : '#fff'};
color: ${props => props.primary ? '#fff' : '#333'};
&:hover {
opacity: 0.8;
}
`;
// Usage
<Button primary>Primary Button</Button>
CSS Class Naming
Use BEM naming conventions:
.user-card {}
.user-card__header {}
.user-card__avatar--large {}
TypeScript Standards
Type Definitions
Prefer using interface
for complex type definitions:
interface User {
id: number;
name: string;
age?: number;
}
function getUser(id: number): Promise<User> {
// ...
}
Component Props Types
Define React component Props using interface
:
interface Props {
visible: boolean;
onClose: () => void;
title?: string;
}
const Modal: React.FC<Props> = ({ visible, onClose, title }) => {
// ...
};
Code Review Points
Team code reviews should focus on the following aspects:
- Compliance with project code style standards
- Whether variable names clearly express intent
- Whether complex logic has appropriate comments
- Whether unnecessary dependencies are introduced
- Whether there are obvious performance issues
- Whether error handling is comprehensive
Documentation Standards
Code standards should be accompanied by documentation. Maintain the following documents:
CODING_GUIDELINES.md
- Detailed coding standardsSTYLE_GUIDE.md
- UI style standardsARCHITECTURE.md
- Project architecture explanationPR_TEMPLATE.md
- Pull Request template
Continuous Integration Configuration
Add code checks to the CI pipeline. Example .github/workflows/ci.yml
:
name: CI
on: [push, pull_request]
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
- run: npm install
- run: npm run lint
- run: npm run type-check
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn