如何在项目中正确配置eslint,规范我们的前端项目

eslint在项目里并不太陌生,通常在使用脚手架时,会默认让你安装执行的eslint,公司项目比较规范时,常常会配置组内统一的eslint规则,eslint帮助我们在开发阶段检查代码是否符合标准规范,统一了我们组内不同项目代码风格,也可以帮助我们养成良好的代码习惯,统一eslint对于项目的可维护性必不可少,今天我们一起学习一下如果改进你项目的规范。

正文开始...

首先我们还是用之前搭建vue的一个项目做从0到1开始配置eslint

安装eslint

js 复制代码
npm i eslint --save-dev

然后我们执行初始化eslint命令

js 复制代码
npm init @eslint/config

此时会让我们选择第三个,并且选择js modules, vue 当你默认选择后就会生成一个文件.eslintrc.js,由于我添加了ts所以默认也会添加@typescript-eslint,我们会发现package.json多了几个插件@typescript-eslint/eslint-plugin@typescript-eslint/parser,并且要安装npm i typescript --save-dev

eslint规则是自己默认选择的配置

js 复制代码
module.exports = {
  env: {
    browser: true,
    es2021: true
  },
  extends: ['eslint:recommended', 'plugin:vue/essential', 'plugin:@typescript-eslint/recommended'],
  parserOptions: {
    ecmaVersion: 'latest',
    parser: '@typescript-eslint/parser',
    sourceType: 'module'
  },
  plugins: ['vue', '@typescript-eslint'],
  rules: {
    indent: ['error', 'tab'],
    'linebreak-style': ['error', 'unix'],
    quotes: ['error', 'single'],
    semi: ['error', 'never']
  }
};

默认生成的规则就是以上

我们运行npx eslint ./src/index.js 执行该命令就会检测对于的文件是否符合eslint默认配置的规则

添加eslint规则

.eslintrc.js

js 复制代码
module.exports = {
  env: {
    browser: true,
    es2021: true
  },
  extends: ['eslint:recommended', 'plugin:vue/essential', 'plugin:@typescript-eslint/recommended'],
  parserOptions: {
    ecmaVersion: 'latest',
    parser: '@typescript-eslint/parser',
    sourceType: 'module'
  },
  plugins: ['vue', '@typescript-eslint'],
  rules: {
    indent: ['error', 'tab'],
    'linebreak-style': ['error', 'unix'],
    quotes: ['error', 'single'],
    semi: ['error', 'always']
  }
};

主要由以下5个部分

  • env 支持的环境,根据.browserslistrc浏览器预设的环境预设对应的规则
js 复制代码
module.exports = {
  env: {
      browser: true,
      es2021: true,
      es6: true
  }
}
  • extends 继承第三方的规则
js 复制代码
module.exports = {
  extends: ['eslint:recommended']
}
  • parserOptions 指定解析器选项
js 复制代码
module.exports = {
    parserOptions: {
      ecmaVersion: 'latest',
      parser: '@typescript-eslint/parser',
      sourceType: 'module'
    }
}
  • plugins 插件
js 复制代码
module.exports = {
  plugins: ['vue', '@typescript-eslint'],
}
  • rules 具体对应规则的设置
js 复制代码
module.exports = {
  rules: {
      semi: 0 // 0 off,1 warn,2 error
  },
}

参考一段之前业务有用用到的统一eslint配置

js 复制代码
// eslint配置
module.exports = {
    root: true,
    env: {
        node: true,
    },
    parserOptions: {
        parser: '@typescript-eslint/parser',
    },
    extends: [
        'plugin:vue/essential',
        'plugin:prettier/recommended',
        '@vue/airbnb',
        '@vue/typescript',
    ],
    rules: {
        'no-undef': 0, // 由于eslint无法识别.d.ts声明文件中定义的变量,暂时关闭
        'no-console': process.env.NODE_ENV === 'production' ? 2 : 0,
        'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0,
        indent: 0,
        'linebreak-style': 0,
        'no-trailing-spaces': 0,
        'class-methods-use-this': 0,
        'import/prefer-default-export': 0,
        'no-restricted-syntax': 0,
        'no-tabs': 0,
        'import/no-unresolved': 0,
        'no-underscore-dangle': 0,
        'comma-dangle': 'off',
        'max-len': 'off',
        camelcase: 'off',
        'object-curly-newline': 0,
        'operator-linebreak': 0,
        'guard-for-in': 0,
        'import/no-webpack-loader-syntax': 0,
        // 不安全项
        'no-param-reassign': 0,
        'no-dupe-class-members': 0,
        'no-unused-vars': 0, // ts里面有校验,可以把eslint 的校验关闭
        // 提示警告
        'no-return-await': 1,
        'import/no-cycle': 1,
        'no-nested-ternary': 1,
        'no-new-func': 1,
        'vue/no-side-effects-in-computed-properties': 1,
        'vue/no-multiple-template-root': 'off', // vue3 模板可以有多个根结点
        'vue/valid-template-root': 'off',
        'vue/no-v-for-template-key': 'off', // vue3  v-for 中template 可以设置key
        'vue/no-v-model-argument': 0,
        'vue/no-use-v-if-with-v-for': 0,
        'import/no-extraneous-dependencies': 1,
        'no-continue': 1,
        'operator-assignment': 1,
        'no-bitwise': 1,
        'prefer-destructuring': 2,
        'array-callback-return': 2,
        'func-names': 2,
        'no-plusplus': 2,
        'no-shadow': 2,
        'no-mixed-operators': 2,
        'no-fallthrough': 2,
        'default-case': 2,
        'no-useless-constructor': 2,
        'no-unused-expressions': ["error", { "allowShortCircuit": true }],
        // 关闭iview input组件,col组件个别标签报错
        'vue/no-parsing-error': [2, { 'x-invalid-end-tag': false }],
        // 保证js、ts项目arrow风格一致
        'arrow-parens': [2, 'always', { requireForBlockBody: false }],
        'implicit-arrow-linebreak': [0, 'beside'],
        // ts 任意枚举报错问题
        'no-shadow': 'off',
        '@typescript-eslint/no-shadow': ['error'],
    },
    overrides: [
        {
            files: ['**/__tests__/*.{j,t}s?(x)', '**/tests/unit/**/*.spec.{j,t}s?(x)'],
            env: {
                jest: true,
            },
        },
    ],
};

选择Airbnb风格

在自定义自己的rules,也可以执行npm init @eslint/config配置社区比较流行的自定义风格,使用Airbnb

当我们选择airbnb风格后,执行npx eslint ./src/index.js 提示index.js有一个规则错误

Expected 1 empty line after import statement not followed by another import import/newline-after-import 我们将第三行换行就行

js 复制代码
import { createApp } from 'vue';
import App from './App.vue';

createApp(App).mount('#app');

我们看下生成的.eslintrc.js这个一般在你项目中多少有看到也可以是json类型

js 复制代码
module.exports = {
  env: {
    browser: true,
    es2021: true,
  },
  extends: [
    'plugin:vue/essential',
    'airbnb-base',
  ],
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module',
  },
  plugins: [
    'vue',
  ],
  rules: {
  },
};

rules有很多的配置,可以参考官方

运行时检测eslint

一般正常情况当我们启动服务时,如果我们代码有写得不规范,开发工具就终端就会给我们提示警告,此时我们需要eslint-loader,只需要这样配置即可

js 复制代码
module.exports = {
  module: {
    rules: [
        {
        test: /\.(js|jsx)$/,
        use: [
          'babel-loader', 'eslint-loader'
        ]
      }
    ]
  }
}

但是官方已经不建议这么用了eslint-loader已经停止了维护,官方建议使用eslint-webpack-plugin

webpack.config.js我们可以这么做

js 复制代码
const ESLintPlugin = require('eslint-webpack-plugin');
module.exports = {
  plugins: [
    new ESLintPlugin()
  ]
}

当我们运行npm run server时就会检查代码错误 提示在utils/index.js中不能使用console,很显然,这条规则并不符合我们的初衷,我只需要在生成环境环境不打印console才行

当我们修改.eslintrc.js时,

js 复制代码
module.exports = {
   rules: {
    'no-console': 0,
    'import/extensions': ['error', 'always']
  }
}

我们将rules规则的noconsole: 0允许使用console,当我修改完时,再次运行,终端就不会报错了

我们再加个规则,max-params:2,函数形参不能到过三个,如果超过三个就会报错

js 复制代码
module.exports = {
  rules: {
    'no-console': 0,
    'import/extensions': ['error', 'always'],
    'max-params': 2
  }
}
js 复制代码
// utils/index.js
function test(a, b, c, d) {
  console.log('hello', a, b, c, d);
}
test(1, 2, 3, 4);

因为默认max-params默认最多就是3个参数,所以在运行时就提示报错了。 于是你改成下面这样就可以了

js 复制代码
// utils/index.js
function test(a, ...rest) {
  console.log('hello', ...rest);
}
test(1, 2, 3, 4);

vscode的eslint插件

除了eslint-webpack-plugin的插件帮我们在代码运行时就可以检测出代码的一些不规范问题,我们通常可以结合vscode插件帮我更友好的提示,我们需要在写代码的时候,编辑器就已经给我们提示错误。

安装完后,打开对应文件,就会有对应的提示 并且你可以通过提示跳转到对应的eslint

.prettierrc自动格式化代码

vscode中装上插件Prettier code formatter

然后在根目录下创建.prettierrc.json文件

json 复制代码
{
  "singleQuote": true,
  "printWidth": 150
}

设置编辑器的代码长度printWidth是150,设置singleQuote单引号。

我们也需要设置一下vscodesettings.json,主要设置参照如下 然后添加一行自动保存功能,这样我们就可以保存时,自动格式化自己的代码

json 复制代码
{
   "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
}

因为eslint既检查了代码又可以根据.eslintrc.js美化代码,但是prettierrc有时会与eslint的配置格式有冲突,所以此时vscode格式化的状态就是混乱的,因此有时候很奇怪,所以你需要改settings.json默认改成eslint,具体可以参考知乎这篇文章prettierrc

网上关于prettierrc的配置有很多,具体上还是看组内统一的规范,这里我贴一份之前项目格式化所用的,估计不同团队的配置绝大数是大同小异。

js 复制代码
// .prettierrc.json
{
  "eslintIntegration": true,
  "printWidth": 100,
  "tabWidth": 2,
  "useTabs": false,
  "semi": true,
  "singleQuote": true,
  "proseWrap": "preserve",
  "arrowParens": "avoid",
  "bracketSpacing": true,
  "disableLanguages": [
    "vue"
  ],
  "endOfLine": "auto",
  "htmlWhitespaceSensitivity": "ignore",
  "ignorePath": ".prettierignore",
  "jsxBracketSameLine": false,
  "jsxSingleQuote": false,
  "requireConfig": false,
  "trailingComma": "es5"
}

总结

  • eslint在项目中的配置,主要利用npm init @eslint/config快速初始化一份eslint配置,在试用前先进行安装npm i eslint --save-dev

  • 开发环境使用eslint-loader,现在采用更多的是eslint-webpack-plugins

  • 采用Airbnb风格格式校验代码

  • .prettierrc.json格式化代码,不过注意与eslint格式冲突的问题。

  • 本文示例code example

相关推荐
wearegogog1233 小时前
基于 MATLAB 的卡尔曼滤波器实现,用于消除噪声并估算信号
前端·算法·matlab
Drawing stars3 小时前
JAVA后端 前端 大模型应用 学习路线
java·前端·学习
品克缤3 小时前
Element UI MessageBox 增加第三个按钮(DOM Hack 方案)
前端·javascript·vue.js
小二·3 小时前
Python Web 开发进阶实战:性能压测与调优 —— Locust + Prometheus + Grafana 构建高并发可观测系统
前端·python·prometheus
小沐°3 小时前
vue-设置不同环境的打包和运行
前端·javascript·vue.js
qq_419854054 小时前
CSS动效
前端·javascript·css
烛阴4 小时前
3D字体TextGeometry
前端·webgl·three.js
桜吹雪4 小时前
markstream-vue实战踩坑笔记
前端
南村群童欺我老无力.4 小时前
Flutter应用鸿蒙迁移实战:性能优化与渐进式迁移指南
javascript·flutter·ci/cd·华为·性能优化·typescript·harmonyos
C_心欲无痕5 小时前
nginx - 实现域名跳转的几种方式
运维·前端·nginx