【Eslint】ESLint 入门教程(幽默风趣版)+最佳实践模板

ESLint 入门教程(幽默风趣版)

一、ESLint 是什么?

ESLint 就像你的代码「私人教练」兼「语法纠察队长」,专门负责:

  1. 揪出代码里的语法错误(比如漏了分号、括号不匹配)
  2. 纠正你的代码风格(比如缩进用 2 空格还是 4 空格)
  3. 防止你写出「迷惑行为」代码(比如变量名叫 abc123

想象你是一个强迫症患者,ESLint 就是帮你治疗的「代码洁癖治疗仪」!


二、为什么需要 ESLint?

1. 避免「代码事故」

// 错误示范:漏了括号,代码直接罢工
if (condition
  console.log('永远不会执行');

// ESLint 会大喊:🚨 缺少右括号!

2. 统一团队代码风格

  • 张三喜欢用 2 空格缩进
  • 李四坚持用 Tab 缩进
  • 王五:都行,但别混着用!

ESLint 一出手,团队从此「缩进统一,天下太平」!

3. 防止「迷惑命名」

// 错误示范:变量名比密码还难猜
let x = 10;
let y = 20;
let z = x + y;

// ESLint 会建议:🤔 请用有意义的变量名!

三、ESLint 安装与配置(实战篇)

1. 安装 ESLint

npm install eslint --save-dev
# 或使用 yarn
# yarn add eslint -D

2. 初始化配置

npx eslint --init

然后按照提示选择:

  1. 你想检查什么问题?(比如语法错误、代码风格)
  2. 你用什么框架?(React/Vue/None)
  3. 你用什么代码风格?(Airbnb/Standard/自定义)

3. 最佳实践配置文件(.eslintrc.js

module.exports = {
  // 继承 Airbnb 风格指南(业界良心)
  extends: ['airbnb', 'prettier'],
  // 指定环境(比如浏览器、Node.js)
  env: {
    browser: true,   //浏览器环境
    node: true,      //node环境
    es2021: true,    //es版本
  },
  // 指定解析器(用 Babel 转译后的代码)
  parser: '@babel/eslint-parser',
  // 指定解析器选项(告诉 ESLint 你的代码用哪些语法)
  parserOptions: {
    ecmaVersion: 2021,          //ecma支持版本
    sourceType: 'module',      //指定代码是模块化还是脚本形式。
    requireConfigFile: false, // 如果你用 Babel 但没有 .babelrc
  },
  // 插件(比如 React 插件)
  plugins: ['react', 'prettier'],
  // 自定义规则(覆盖默认规则)
  rules: {
    // 允许在 JSX 中使用箭头函数(React 开发必备)
    'react/jsx-props-no-spreading': 'off',
    // 允许使用 console.log(开发时方便,生产环境再用其他工具处理)
    'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    // 强制使用单引号(和 Prettier 统一)
    quotes: ['error', 'single'],
    // 关闭行尾分号要求(和 Prettier 统一)
    'semi': ['error', 'never'],
    // 启用 Prettier 自动格式化
    'prettier/prettier': ['error'],
  },
  // 忽略文件(比如 build 目录)
  ignorePatterns: ['dist', 'build', 'node_modules'],
};

4. 配置 Prettier(代码格式化神器)

npm install prettier eslint-config-prettier eslint-plugin-prettier --save-dev

然后创建 .prettierrc 文件:

{
  "singleQuote": true, //是否开启单引号
  "semi": false,       //是否必须写分号
  "trailingComma": "es5", //对象数组最后元素是否加逗号
  "printWidth": 80       //打印宽度
}

5. 配置编辑器(VS Code 示例)

  1. 安装插件:
    • ESLint
    • Prettier - Code formatter
  2. 设置 settings.json
{
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "eslint.alwaysShowStatus": true,
  "eslint.validate": ["javascript", "javascriptreact", "typescript", "typescriptreact"]
}

四、常见规则解释(用生活场景类比)

1. no-unused-vars(禁止未使用的变量)

  • 🚫 错误:
function foo() {
  const unusedVar = 10; // 🤷‍♂️ 定义了但没用
  return 42;
}
  • ✅ 正确:
function foo() {
  const usedVar = 10; // 🎉 定义了并且用了
  return usedVar * 4.2;
}
  • 类比:你买了一堆零食,但从来不吃,最后都过期了——浪费!

2. eqeqeq(强制使用 === 而不是 ==

  • 🚫 错误:
if (a == b) { ... } // 😱 宽松相等,容易出错
  • ✅ 正确:
if (a === b) { ... } // 🎯 严格相等,安全!
  • 类比:你问朋友「你身高 180 吗?」
    • 宽松版本:== → 朋友说「我 180.5cm,四舍五入算 180 吧」
    • 严格版本:=== → 朋友说「我 180.5cm,不算 180」

3. max-len(限制行长度)

  • 🚫 错误:
const superLongVariableNameThatBreaksTheLineLimitAndMakesTheCodeHardToRead = 'value';
  • ✅ 正确:
const shortVarName = 'value'; // 📏 行长度不超过 80 字符
  • 类比:你写论文,一行写到屏幕边缘还不换行——眼睛疼!

4. react/jsx-uses-react(React 组件必须导入 React)

  • 🚫 错误:
function MyComponent() {
  return <div>Hello</div>; // 😱 忘记导入 React
}
  • ✅ 正确:
import React from 'react'; // 🎉 必须导入 React

function MyComponent() {
  return <div>Hello</div>;
}
  • 类比:你做菜,但忘记买食材——巧妇难为无米之炊!

五、实际业务场景应用

1. React 项目配置

// .eslintrc.js
module.exports = {
  extends: [
    'airbnb',
    'plugin:react/recommended',
    'plugin:jsx-a11y/recommended',
    'prettier',
  ],
  plugins: ['react', 'jsx-a11y', 'prettier'],
  rules: {
    // React 特定规则
    'react/jsx-filename-extension': ['error', { extensions: ['.jsx', '.tsx'] }],
    'react/prop-types': 'off', // 如果你用 TypeScript,可以关闭
    'react/jsx-one-expression-per-line': 'off', // 允许单行 JSX 表达式
    // 关闭行尾分号(和 Prettier 统一)
    'semi': ['error', 'never'],
    // 启用 Prettier 自动格式化
    'prettier/prettier': ['error'],
  },
};

2. TypeScript 项目配置

npm install --save-dev @typescript-eslint/parser @typescript-eslint/eslint-plugin
// .eslintrc.js
module.exports = {
  extends: [
    'airbnb',
    'airbnb-typescript',
    'plugin:@typescript-eslint/recommended',
    'prettier',
  ],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaVersion: 2021,
    sourceType: 'module',
    project: './tsconfig.json', // 指定 TypeScript 配置文件
  },
  plugins: ['@typescript-eslint', 'prettier'],
  rules: {
    // TypeScript 特定规则
    '@typescript-eslint/explicit-module-boundary-types': 'off', // 允许省略返回类型
    '@typescript-eslint/no-explicit-any': 'warn', // 警告使用 any 类型
    // 关闭行尾分号(和 Prettier 统一)
    'semi': ['error', 'never'],
    // 启用 Prettier 自动格式化
    'prettier/prettier': ['error'],
  },
};

3. 自定义规则(业务场景)

假设你有一个业务规则:所有 API 请求的 URL 必须以 /api 开头

方法一:使用 eslint-plugin-import
// .eslintrc.js
module.exports = {
  rules: {
    'import/no-internal-modules': [
      'error',
      {
        allow: ['^@/api/.*'], // 允许导入 @/api/ 下的模块
      },
    ],
  },
};
方法二:自定义规则(高级)
  1. 创建 eslint-plugin-custom-rules 目录。
  2. 创建 lib/rules/api-url-must-start-with-api.js
module.exports = {
  meta: {
    type: 'suggestion',
    docs: {
      description: 'API URL 必须以 /api 开头',
      category: 'Possible Errors',
      recommended: false,
    },
    schema: [],
  },
  create(context) {
    return {
      Literal(node) {
        if (typeof node.value === 'string' && node.value.startsWith('/api')) {
          return;
        }
        if (node.parent.type === 'CallExpression' && 
            node.parent.callee.name === 'fetch' && 
            typeof node.value === 'string') {
          context.report({
            node,
            message: 'API URL 必须以 /api 开头',
          });
        }
      },
    };
  },
};
  1. 配置 .eslintrc.js
module.exports = {
  plugins: ['custom-rules'],
  rules: {
    'custom-rules/api-url-must-start-with-api': 'error',
  },
};

六、常见问题解决

1. 为什么 ESLint 不生效?

  • 检查 .eslintrc.js 是否在项目根目录。
  • 检查编辑器是否安装了 ESLint 插件。
  • 检查 package.json 中是否安装了 ESLint 依赖。

2. 如何忽略某些文件或规则?

  • 忽略文件:在 .eslintignore 中添加:
build/
dist/
node_modules/
  • 忽略单行规则:
// eslint-disable-next-line no-console
console.log('这条警告会被忽略');
  • 忽略多行规则:
/* eslint-disable */
console.log('所有警告都会被忽略');
console.log('直到这里');
/* eslint-enable */

3. 如何修复所有 ESLint 错误?

npx eslint --fix .

七、总结

  1. ESLint 的核心作用
    • 语法检查(防止代码跑不起来)
    • 代码风格统一(防止团队撕逼)
    • 代码质量提升(防止写出迷惑代码)
  2. 最佳实践配置
    • 继承 Airbnb 风格指南
    • 结合 Prettier 自动格式化
    • 根据项目类型(React/Vue/TypeScript)调整规则
  3. 实际业务场景
    • 自定义规则(比如 API URL 规范)
    • 团队共享配置(通过 extends
    • 自动化修复(--fix 命令)

现在,你已经掌握了 ESLint 的「武功秘籍」,快去驯服你的代码吧!记住:代码不规范,同事两行泪 😉

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值