2
头图

In the previous project, the eslint check was ignored, resulting in more than 2,000 errors (இдஇ; ) in one run npm run lint It took two or three days to complete it and make a summary of errors.

Environment and Configuration

The project uses vue@3.2 + vite + ant-design@6.0
For the usage of eslint configuration, please refer to: ESLint Chinese
eslint has a plugin specifically for vue: eslint-plugin-vue
Roughly paste the version dependencies

 devDependencies: {
    "@babel/eslint-parser": "^7.18.2",
    "eslint": "^8.7.0",
    "eslint-config-prettier": "^8.3.0",
    "eslint-import-resolver-alias": "^1.1.2",
    "eslint-plugin-import": "^2.25.4",
    "eslint-plugin-jest": "^25.7.0",
    "eslint-plugin-vue": "^8.3.0",
}

The configuration of eslint is in JS file format. After several revisions, I have forgotten the content at the beginning. Only the basic configuration is as follows:

 // .eslintrc.js
module.exports = {
    // 只作用于当前目录
    root: true,
    // 运行环境
    env: {
        node: true,
        es6: true,
    },
    // 解析器
    parser: '@babel/eslint-parser',
    // 解析器选项
    parserOptions: {
        sourceType: 'module',
    },
    // 插件
    plugins: ['import'],
    // 扩展配置
    extends: [
        'plugin:vue/vue3-recommended',
        'plugin:import/recommended',
        'prettier',
    ],
    // 启用规则
    rules: {},
    // 全局变量
    globals: {
        h: true,
    },
    // 为指定文件指定处理器
    overrides: [
        {
            files: ['*.vue', '*.jsx'],
            parser: 'vue-eslint-parser',
            parserOptions: {
                ecmaVersion: 2018,
            },
            rules: {}
        }
    ],
}

ERROR: Parsing error: Unexpected token .

error code:

 const isOpen = data?.form?.isOpen || false;

It turns out that the optional chain operator ( ?. ) is not recognized, but the extension operator is no problem. After reading the configuration of eslint, it is found that the version of ECMAScript is set to 2018 (ES9), and the optional chain operator It is ES2020 (if I remember correctly), just modify the configuration

 // .eslintrc.js
module.exports = {
    parserOptions: {
        // ES版本,最新可设置 2022 or "latest",overrides 中配置了有需要也要同步修改
        ecmaVersion: 2020,
        sourceType: 'module',
    }
}

ERROR: Unable to resolve path to module

error code:

 import Upload from '@/components/upload/index.vue'

Path reference error? ? It looks fine, vite.config.js is clearly configured with a short chain

 resolve: {
    alias: {
        '@': pathResolve('src'),
    }
}

But eslint does not automatically read the configuration of vite, so eslint should also add the corresponding configuration:

 // .eslintrc.js
module.exports = {
    settings: {
        'import/resolver': {
            alias: {
                map: ['@': './src']
            }
        }
    }
}

In addition, you need to add the suffix .vue to import the vue file, otherwise the same error will be reported.


ERROR: 'ref' is not defined

error code:

 setup(){
    const isOpen = ref(false);
    return {
        isOpen,
    }
}

There is no error when running, why is it suddenly undefined? ?
Wait, because of laziness, vue's syntactic sugar is unplugin-auto-import automatically introduced by each file:

 // vite.config.js
import autoImport from 'unplugin-auto-import/vite';

autoImport({
    imports: [
        'vue',
        'vue-router',
    ]
})

So also let eslint know, first generate a file containing all variables:

 // vite.config.js
autoImport({
    ...last,
    eslintrc: {
        // 已存在文件设置默认 false,需要更新时再打开,防止每次更新都重新生成
        enabled: false,
        // 生成文件地址和名称
        filepath: './.eslintrc-auto-import.json',
        globalsPropValue: true,
    }
})

The above enabled is recommended to be closed after generating the file, otherwise it will be regenerated every update.
Extending to eslint:

 // .eslintrc.js
module.exports = {
    extends: [
        'plugin:vue/vue3-recommended',
        'plugin:import/recommended',
        'prettier',
        './.eslintrc-auto-import.json'
    ],
}

ERROR: vue/no-mutating-props

error code:

 <!-- parent.vue -->
<template>
    <Child v-model:open="openModal" />
</template>
<script>
export default{
    setup(){
        const openModal = ref(false);
        return {
            openModal,
        }
    }
}
</script>

<!-- child.vue -->
<template>
    <a-modal v-model:visible="open"></a-modal>
</template>

<script>
export default{
    props: {
        open: {
            type: Boolean,
            default: true,
        }
    },
}
</script>

This is a low-level error, vue3 supports two-way binding of multiple parameters, but subcomponents cannot be directly modified props , you need to convert it:

  • Method 1: Replace with computed

     <template>
      <a-modal v-model:visible="isOpen"></a-modal>
    </template>
    
    <script>
    export default{
      props: {
          open: {
              type: Boolean,
              default: true,
          }
      },
      setup(props, { emit }){
          const isOpen = computed({
              get: () => {
                  return props.open;
              },
              set: (value) => {
                  emit('update:open', value);
              },
          });
    
          return {
              isOpen,
          }
      },
    }
    </script>
  • Method 2: Use watch to monitor

     <template>
      <a-modal v-model:visible="isOpen"></a-modal>
    </template>
    
    <script>
    export default{
      props: {
          open: {
              type: Boolean,
              default: true,
          }
      },
      setup(props, { emit }){
          const isOpen = ref(props.open);
          
          watch(
              () => isOpen.value,
              (value) => emit('update:open', value)
          );
    
          return {
              isOpen,
          }
      },
    }
    </script>

ERROR: no-console

error code:

 console.log(data);

The rules of eslint set that there cannot be console , of course, you can change the configuration:

 // .eslintrc.js
rules: {
    'no-console': 'off',
    // or:
    'no-console': [2, { allow: ['warn', 'error'] }],
    // or:
    'no-console': process.env.NODE_ENV === 'production' ? [2, { allow: ['warn', 'error'] }] : 'off'
}

This error is mentioned to introduce the following problems. In some places, you need to print but you don't want eslint to report an error. You can let it ignore the check:

 // 忽略整个文件在第一行加
/* eslint-disable */

// 忽略一段代码检查
/* eslint-disable */
...this our codes;
/* eslint-enable */

// 忽略一行代码检查
console.log(data); // eslint-disable-line

// 忽略下一行代码检查
// eslint-disable-next-line
console.log(data);

So what about in <template> ?

 <template>
    <!-- eslint-disable -->
    <div v-for="item in options">{{ item }}</div>
</template>

Then it is found that it does not work, it will report vue/require-v-for-key error, and the annotation fails.
I found various articles and vue/comment-directive found that it was my own pot . , a look at the file configuration of eslint is really closed:

 // .eslintrc.js
rules: {
    'vue/comment-directive': 'off',
}

Changed to error , perfect ؏؏☝ᖗ乛◡乛ᖘ☝؏؏


knock off.


Shyla
1.5k 声望148 粉丝

FE programmer