面试题答案
一键面试- 创建规则文件:
- 在项目根目录下创建一个
eslint-rules
文件夹(可自定义)。 - 在该文件夹下创建一个新的JavaScript文件,例如
max - 3 - params.js
。
- 在项目根目录下创建一个
- 编写规则代码:
module.exports = { create(context) { return { FunctionDeclaration(node) { const paramCount = node.params.length; if (paramCount > 3) { context.report({ node, message: 'Function parameters should not exceed 3.' }); } }, FunctionExpression(node) { const paramCount = node.params.length; if (paramCount > 3) { context.report({ node, message: 'Function parameters should not exceed 3.' }); } }, ArrowFunctionExpression(node) { const paramCount = node.params.length; if (paramCount > 3) { context.report({ node, message: 'Function parameters should not exceed 3.' }); } } }; } };
- 配置ESLint:
- 在项目根目录下找到
.eslintrc
文件(如果没有则创建一个,支持.eslintrc.js
、.eslintrc.json
等格式,这里以.eslintrc.js
为例)。 - 在
.eslintrc.js
中添加以下内容:
module.exports = { //...其他配置 rules: { 'max - 3 - params': 'error' }, plugins: [ // 假设规则在eslint - rules文件夹下,可根据实际路径调整 new require('eslint - plugin - eslint - relative - paths')({ rulesDir: './eslint - rules' }) ] };
- 如果使用
.eslintrc.json
,配置如下:
{ //...其他配置 "rules": { "max - 3 - params": "error" }, "plugins": [ // 假设规则在eslint - rules文件夹下,可根据实际路径调整 { "module": "eslint - plugin - eslint - relative - paths", "options": { "rulesDir": "./eslint - rules" } } ] }
- 在项目根目录下找到
- 安装必要插件(可选):
- 如果在配置ESLint时使用了
eslint - plugin - eslint - relative - paths
插件(用于相对路径加载自定义规则),需要安装它:
npm install eslint - plugin - eslint - relative - paths --save - dev
- 如果在配置ESLint时使用了
这样就自定义了一个ESLint规则来检测JavaScript代码中函数参数数量不超过3个。