前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >项目eslint从零到一

项目eslint从零到一

作者头像
Maic
发布2022-07-28 12:37:40
1.5K0
发布2022-07-28 12:37:40
举报
文章被收录于专栏:Web技术学苑Web技术学苑

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

正文开始...

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

安装eslint

代码语言:javascript
复制
npm i eslint --save-dev

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

代码语言:javascript
复制
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规则是自己默认选择的配置

代码语言:javascript
复制
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中,主要有以下5个部分

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

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

代码语言:javascript
复制
// 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我们将第三行换行就行

代码语言:javascript
复制
import { createApp } from 'vue';
import App from './App.vue';

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

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

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

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

运行时检测eslint

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

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

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

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

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

当我们运行npm run server时就会检查代码错误

提示在utils/index.js中不能使用console,很显然,这条规则并不符合我们的初衷,我只需要在生产环境环境不打印console才行

当我们修改.eslintrc.js时,

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

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

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

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

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

代码语言:javascript
复制
// 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文件

代码语言:javascript
复制
{
  "singleQuote": true,
  "printWidth": 150
}

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

我们也需要设置一下vscodesettings.json,主要设置参照如下

然后添加一行自动保存功能,这样我们就可以保存时,自动格式化自己的代码

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

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

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

代码语言:javascript
复制
// .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[4]

参考资料

[1]参考官方: https://eslint.org/docs/rules/

[2]eslint-loader: https://www.npmjs.com/package/eslint-loader

[3]prettierrc: https://zhuanlan.zhihu.com/p/347339865

[4]code example: https://github.com/maicFir/lessonNote/tree/master/webpack/webpack-06-eslint

本文参与?腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-06-18,如有侵权请联系?cloudcommunity@tencent.com 删除

本文分享自 Web技术学苑 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体同步曝光计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 安装eslint
    • 添加eslint规则
    • 选择Airbnb风格
    • 运行时检测eslint
    • vscode的eslint插件
    • 总结
    • 参考资料
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
    http://www.vxiaotou.com