About esLint code specification detection

Recently, I need to configure front-end code specification detection in the project. Here are some detection files configured after looking at some documentsCopy the code

Dependency packages required

npm i babel-eslint npm i eslint npm i eslint-loader npm i eslint-plugin-vue npm i husky npm i lint-staged npm i vue-eslint-parser

1. Eslint configuration file description

1.1. eslintrc.js file configuration

/* eslint-disable no-magic-numbers */
module.exports = {
  'root': true.// This is used to tell ESLint that the current configuration file cannot be looked up by its parent
  'env': {
    'browser': true.// This specifies the global variable of the environment. The following configuration specifies the browser environment
    'es6': true.'node': true
  },
  'extends': ['plugin:vue/recommended'.'eslint:recommended'].// This item is used to configure the detection standard style
  'parser': 'vue-eslint-parser'.'parserOptions': {
    'ecmaVersion': 2020.'parser': 'babel-eslint'.// This is used to specify esLint parsers. Parsers must conform to the rules. The babel-esLint parser is a wrapper around the Babel parser that parses with ESLint
    'sourceType': 'module' // This item is used to specify javaScript language type and style, sourceType is used to specify the js import method, the default is script, set to module, refers to a block import method
  },
  // This is used to provide plugins, the plugin name omits eslint-plugin-, and the following configuration is used to standardize vUE
  'plugins': [
    'vue'].// The following rules are used to set custom specification code
  'rules': {
    'vue/max-attributes-per-line': [2, {
      'singleline': 10.'multiline': {
        'max': 1.'allowFirstLine': false}}].'vue/singleline-html-element-content-newline': 'off'.'vue/multiline-html-element-content-newline': 'off'.'vue/name-property-casing': ['error'.'PascalCase'].'vue/no-v-html': 'off'.'vue/html-self-closing': ['error', {
      'html': {
        'void': 'never'.'normal': 'always'.'component': 'always'
      },
      'svg': 'always'.'math': 'always'}].'accessor-pairs': 2.'arrow-spacing': [2, {
      'before': true.'after': true}].'block-spacing': [2.'always'].'brace-style': [2.'1tbs', {
      'allowSingleLine': true}].'camelcase': [0, {
      'properties': 'always'}].'comma-dangle': [2.'never'].'comma-spacing': [2, {
      'before': false.'after': true}].'comma-style': [2.'last'].'constructor-super': 2.'curly': [2.'multi-line'].'dot-location': [2.'property'].'eol-last': 2.'eqeqeq': ['error'.'always', { 'null': 'ignore'}].'generator-star-spacing': [2, {
      'before': true.'after': true}].'handle-callback-err': [2.'^(err|error)$'].'indent': [2.2, {
      'SwitchCase': 1}].'jsx-quotes': [2.'prefer-single'].'key-spacing': [2, {
      'beforeColon': false.'afterColon': true}].'keyword-spacing': [2, {
      'before': true.'after': true}].'new-cap': [2, {
      'newIsCap': true.'capIsNew': false}].'new-parens': 2.'no-array-constructor': 2.'no-caller': 2.'no-console': 'off'.'no-class-assign': 2.'no-cond-assign': 2.'no-const-assign': 2.'no-control-regex': 0.'no-delete-var': 2.'no-dupe-args': 2.'no-dupe-class-members': 2.'no-dupe-keys': 2.'no-duplicate-case': 2.'no-empty-character-class': 2.'no-empty-pattern': 2.'no-eval': 2.'no-ex-assign': 2.'no-extend-native': 2.'no-extra-bind': 2.'no-extra-boolean-cast': 2.'no-extra-parens': [2.'functions'].'no-fallthrough': 2.'no-floating-decimal': 2.'no-func-assign': 2.'no-implied-eval': 2.'no-inner-declarations': [2.'functions'].'no-invalid-regexp': 2.'no-irregular-whitespace': 2.'no-iterator': 2.'no-label-var': 2.'no-labels': [2, {
      'allowLoop': false.'allowSwitch': false}].'no-lone-blocks': 2.'no-mixed-spaces-and-tabs': 2.'no-multi-spaces': 2.'no-multi-str': 2.'no-multiple-empty-lines': [2, {
      'max': 1}].'no-native-reassign': 2.'no-negated-in-lhs': 2.'no-new-object': 2.'no-new-require': 2.'no-new-symbol': 2.'no-new-wrappers': 2.'no-obj-calls': 2.'no-octal': 2.'no-octal-escape': 2.'no-path-concat': 2.'no-proto': 2.'no-redeclare': 2.'no-regex-spaces': 2.'no-return-assign': [2.'except-parens'].'no-self-assign': 2.'no-self-compare': 2.'no-sequences': 2.'no-shadow-restricted-names': 2.'no-spaced-func': 2.'no-sparse-arrays': 2.'no-this-before-super': 2.'no-throw-literal': 2.'no-trailing-spaces': 2.'no-undef': 2.'no-undef-init': 2.'no-unexpected-multiline': 2.'no-unmodified-loop-condition': 2.'no-unneeded-ternary': [2, {
      'defaultAssignment': false}].'no-unreachable': 2.'no-unsafe-finally': 2.'no-unused-vars': [2, {
      'vars': 'all'.'args': 'none'}].'no-useless-call': 2.'no-useless-computed-key': 2.'no-useless-constructor': 2.'no-useless-escape': 0.'no-whitespace-before-property': 2.'no-with': 2.'one-var': [2, {
      'initialized': 'never'}].'operator-linebreak': [2.'after', {
      'overrides': {
        '? ': 'before'.':': 'before'}}].'padded-blocks': [2.'never'].'quotes': [2.'single', {
      'avoidEscape': true.'allowTemplateLiterals': true}].'semi': [2.'never'].'semi-spacing': [2, {
      'before': false.'after': true}].'space-before-blocks': [2.'always'].'space-before-function-paren': [2.'never'].'space-in-parens': [2.'never'].'space-infix-ops': 2.'space-unary-ops': [2, {
      'words': true.'nonwords': false}].'spaced-comment': [2.'always', {
      'markers': ['global'.'globals'.'eslint'.'eslint-disable'.'*package'.'! '.', ']}],'template-curly-spacing': [2.'never'].'use-isnan': 2.'valid-typeof': 2.'wrap-iife': [2.'any'].'yield-star-spacing': [2.'both'].'yoda': [2.'never'].'prefer-const': 2.'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0.'object-curly-spacing': [2.'always', {
      objectsInObjects: false}].'array-bracket-spacing': [2.'never']}}Copy the code

1.2 Webpack.config. js file configuration

// webpack.config.js
module.exports = {
  / /... Other options
  // Since our project uses WebPack and the code is compiled by Babel, some of the syntax handled by Babel may not support ESLint well
  // Configure the following modules to perform detection before package compilation
  module: {
    rules: [{enforce: 'pre'.// Force eslint-loader to run first
        test: /\.(js|vue)$/,
        loader: 'eslint-loader'.exclude: /node_modules/}}}]Copy the code
  • The eslint-loader is not normally configured in webpack, which can affect the packaging speed, as described below. In Git, the necessary code is checked and packaged directly

1.3 Now that the two basic ESLint files are configured, how do YOU enable them to detect our code

{
  "name": ""."version": ""."private": true."scripts": {
    "serve": "vue-cli-service serve"."build": "vue-cli-service build".// * Directory represents all files
    "fix": "eslint src/**/**/*.{js,vue} --fix".// NPM performs automatic repair
    "lint": "eslint src/**/**/*.{js,vue}".// NPM performs detection
  },
Copy the code
  • (1) “lint” : if you use NPM run Lint, esLint will be enabled. If you use NPM run Lint, any code that does not conform to the rules will be detected, in which path, on which line, and why.

  • (2) “fix” : Using NPM run fix enables simple code that esLint can assume can be fixed automatically by default

1.4 Since it is not always remembered to go to Lint before committing code, we added a code configuration to check the code every time committing code

  / / husky plug-in
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"}},// Lint-staged is configured to perform tests at COMMIT time
  "lint-staged": {
    "src/**/**/*.{js,json,css,vue}": [
      "eslint src/**/**/*.{js,vue}"."git add"]},Copy the code
  • At this time, after going back to the error code file to correct the code, add and commit again can make the commit, then can push to the remote repository, and then directly pack, without configuring the webpack file for ESlint-loader, prompting the packaging speed

2. Plugins for real-time detection of code writing specifications

2.1 we are using the vscode compiler, which contains a plugin called eslint that can check the code writing specification in real time and provide prompts. If you are interested, you can search the plugin library

2.2 If automatic restoration is required after downloading, you need to configure it in the Settings

/ / configuration eslint
// Save automatic formatting
"editor.formatOnSave": true."eslint.autoFixOnSave": true.By default, only.js files are supported
"eslint.validate": [
    "javascript".// Check js files with esLint rules
    "javascriptreact"."vue-html",
    {
    "language": "vue".// Check vue files
    "autoFix": true   // Enable saving autofix for vue files
    },
    {
    "language": "html"."autoFix": true},]."eslint.run": "onSave"."files.autoSave": "afterDelay"
Copy the code

3. Attached is the basic project catalog

  - src	
	  - views
	     - Login.vue
	     - Home.vue
	  - App.vue
	  - main.js
	.eslintrc.js
	package.json
	vue.config.js
	webpack.config.js
Copy the code