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.jsfunction test(a, b, c, d) {  console.log('hello', a, b, c, d);}test(1, 2, 3, 4);


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

// utils/index.jsfunction 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技术学苑
好好学习,天天向上!