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 Workflowon:push:branches: ["main"]# 推送至main分支时触发pull_request:branches: ["main"]# 创建针对main分支的PR时触发jobs:review:runs-on: ubuntu-lateststeps:- name: Checkout codeuses: actions/checkout@v3- name: Set up Node.jsuses: actions/setup-node@v3with:node-version: '18'# 使用Node.js 18版本cache: 'yarn'# 缓存yarn依赖,加速安装- name: Install dependenciesrun: yarn install --frozen-lockfile# 安装项目依赖- name: Run ESLint and Prettierrun: 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 .验证是否生效。代码审查不仅要检查风格和潜在错误,还需确保功能正确性。可使用Jest等单元测试框架编写测试用例,覆盖核心逻辑。
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会输出测试结果(如通过/失败的用例数量)。