关于javascript:项目eslint从0到1

9次阅读

共计 6509 个字符,预计需要花费 17 分钟才能阅读完成。

eslint在我的项目里并不太生疏,通常在应用脚手架时,会默认让你装置执行的 eslint, 公司我的项目比拟标准时,经常会配置组内对立的eslint 规定,eslint帮忙咱们在开发阶段查看代码是否合乎标准规范,对立了咱们组内不同我的项目代码格调,也能够帮忙咱们养成良好的代码习惯,对立 eslint 对于我的项目的可维护性必不可少,明天咱们一起学习一下如果改良你我的项目的标准。

注释开始 …

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

装置 eslint

npm i eslint --save-dev

而后咱们执行初始化 eslint 命令

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规定是本人默认抉择的配置

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

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 浏览器预设的环境预设对应的规定

    module.exports = {
    env: {
        browser: true,
        es2021: true,
        es6: true
    }
    }
  • extends 继承第三方的规定

    module.exports = {extends: ['eslint:recommended']
    }
  • parserOptions 指定解析器选项

    module.exports = {
      parserOptions: {
        ecmaVersion: 'latest',
        parser: '@typescript-eslint/parser',
        sourceType: 'module'
      }
    }
  • plugins 插件

    module.exports = {plugins: ['vue', '@typescript-eslint'],
    }
  • rules 具体对应规定的设置

    module.exports = {
    rules: {semi: 0 // 0 off,1 warn,2 error},
    }

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

    // 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
咱们将第三行换行就行

import {createApp} from 'vue';
import App from './App.vue';

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

咱们看下生成的 .eslintrc.js 这个个别在你我的项目中多少有看到也能够是 json 类型

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,只须要这样配置即可

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

然而官网曾经不倡议这么用了 eslint-loader 曾经进行了保护,官网倡议应用eslint-webpack-plugin

webpack.config.js 咱们能够这么做

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

当咱们运行 npm run server 时就会查看代码谬误

提醒在 utils/index.js 中不能应用 console, 很显然,这条规定并不合乎咱们的初衷,我只须要在生成环境环境不打印console 才行

当咱们批改 .eslintrc.js 时,

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

咱们将 rules 规定的 noconsole: 0 容许应用console, 当我批改完时,再次运行,终端就不会报错了

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

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

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

// 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 文件

{
  "singleQuote": true,
  "printWidth": 150
}

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

咱们也须要设置一下 vscodesettings.json, 次要设置参照如下

而后增加一行主动保留性能, 这样咱们就能够保留时,主动格式化本人的代码

{
   "editor.codeActionsOnSave": {"source.fixAll.eslint": true},
}

因为 eslint 既查看了代码又能够依据 .eslintrc.js 丑化代码,然而 prettierrc 有时会与 eslint 的配置格局有抵触,所以此时 vscode 格式化的状态就是凌乱的,因而有时候很奇怪,所以你须要改 settings.json 默认改成eslint, 具体能够参考知乎这篇文章 prettierrc

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

// .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

欢送关注公众号:Web 技术学苑
好好学习,天天向上!

正文完
 0