Ubuntu上JavaScript代碼審查的實施方法
ESLint是JavaScript/React項目首選的靜態代碼分析工具,可檢測語法錯誤、代碼風格不一致、潛在邏輯問題(如未使用的變量、不安全的DOM操作),并支持自定義規則。
npm install eslint --save-dev安裝ESLint;接著執行npx eslint --init,根據提示選擇項目配置(如“Use a popular style guide”或“Answer questions about your style”),生成.eslintrc.js(或.eslintrc.json)配置文件。npx eslint .(檢查當前目錄及子目錄所有JS文件)或npx eslint src/(僅檢查src目錄),終端會輸出錯誤和警告信息(如no-unused-vars表示未使用變量)。Prettier專注于代碼格式統一(如縮進、引號、分號、換行),與ESLint配合使用可避免風格爭議。
npm install --save-dev prettier安裝;創建.prettierrc文件(如{ "semi": true, "singleQuote": true, "tabWidth": 2 })定義格式規則。npx prettier --write "src/**/*.{js,jsx}",自動格式化src目錄下所有JS/JSX文件。通過Husky設置Git鉤子(如pre-commit),在提交代碼前自動運行ESLint和Prettier,確保只有符合規范的代碼能被提交;Lint-Staged則僅檢查暫存的文件,提升效率。
npm install husky lint-staged --save-dev安裝。"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{js,jsx}": [
"eslint --fix", // 自動修復可修復的問題
"prettier --write", // 格式化代碼
"git add" // 將修復后的文件重新加入暫存區
]
}
此配置會在git commit時自動觸發ESLint修復和Prettier格式化。將代碼審查流程集成到GitHub Actions,實現每次推送(push)或拉取請求(Pull Request)時自動運行檢查,確保主分支代碼質量。
.github/workflows目錄下創建code-review.yml文件,內容如下:name: Code Review Workflow
on:
push:
branches: ["main"] # 推送至main分支時觸發
pull_request:
branches: ["main"] # 創建針對main分支的PR時觸發
jobs:
review:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: '18' # 使用Node.js 18版本
cache: 'yarn' # 緩存yarn依賴,加速安裝
- name: Install dependencies
run: yarn install --frozen-lockfile # 安裝項目依賴
- name: Run ESLint and Prettier
run: npm run lint # 執行package.json中的lint腳本(需提前配置)
package.json中添加lint腳本:"scripts": {
"lint": "eslint src/ --ext .js,.jsx && prettier --check 'src/**/*.{js,jsx}'"
}
此腳本會檢查src目錄下所有JS/JSX文件的ESLint錯誤和Prettier格式問題。若項目有特殊編碼規范(如“函數參數不超過3個”“禁止使用alert”),可通過自定義ESLint規則實現。
eslint/rules/custom-rule.js,編寫規則邏輯(如檢查函數參數數量):module.exports = {
meta: {
type: 'suggestion',
docs: {
description: '限制函數參數數量不超過3個',
category: 'Best Practices',
recommended: false
},
schema: [{ type: 'integer', minimum: 1 }], // 允許配置最大參數數
messages: {
tooManyParams: '函數參數過多({{count}}個),最多允許{{max}}個。'
}
},
create(context) {
const maxParams = context.options[0] || 3; // 默認最大3個參數
return {
FunctionDeclaration(node) {
if (node.params.length > maxParams) {
context.report({
node,
messageId: 'tooManyParams',
data: { count: node.params.length, max: maxParams }
});
}
},
FunctionExpression(node) {
if (node.params.length > maxParams) {
context.report({
node,
messageId: 'tooManyParams',
data: { count: node.params.length, max: maxParams }
});
}
}
};
}
};
.eslintrc.js中引入自定義規則:module.exports = {
rules: {
'custom-rule': ['error', 3] // 啟用自定義規則,設置最大參數數為3
},
plugins: ['custom-plugin'] // 聲明自定義規則插件(需創建eslint/plugins/custom-plugin/index.js導出規則)
};
自定義規則需通過eslint --print-config .驗證是否生效。代碼審查不僅要檢查風格和潛在錯誤,還需確保功能正確性??墒褂肑est等單元測試框架編寫測試用例,覆蓋核心邏輯。
npm install --save-dev jest安裝。__tests__/example.test.js文件,編寫測試代碼(如測試一個加法函數):const add = require('../src/add'); // 假設add函數在src/add.js中
test('adds 1 + 2 to equal 3', () => {
expect(add(1, 2)).toBe(3);
});
npm test,Jest會輸出測試結果(如通過/失敗的用例數量)。