vue3+vite+ts安装eslint问题记录&解决

2023.08

安装eslint

参照 eslint官网步骤 https://eslint.org/docs/latest/use/getting-started

npm init @eslint/config

选择配置

  1. 选择模式 to check syntax, find problems, and enforce code style
  2. 选择语言模块 JavaScript
  3. 语言框架 vue
  4. 是否使用ts yes
  5. 代码在哪里运行 Browser
  6. 风格指南 standard
  7. 配置文件格式 JavaScript
  8. 是否现在安装,用什么包管理器来下载 yarn

此时页面会出现一个.eslintrc.cjs文件

配置package.json

增加lint命令

"scripts": {
    "dev": "vite",
    "build": "vue-tsc && vite build",
    "preview": "vite preview",
    "lint": "eslint  './src/**/*.{js,jsx,vue,ts,tsx}' --fix"
  },

执行yarn lint命令

1.报错 parserOptions.project

Error: Error while loading rule '@typescript-eslint/dot-notation': You have used a rule which requires parserServices to be generated. You must therefore provide a value for the "parserOptions.project" property for @typescript-eslint/parser.

解决方式:
在.eslintrc.cjs 添加配置
配置对应TypeScript对应的语法解析器

"parserOptions": {
      .....
        "parser": "@typescript-eslint/parser",
        "project": './tsconfig.json', 
       ....
    },

esLint 默认的 parser ,只转换 js,默认支持 ES5 的语法,所以t项目需要通过制定 parserOptions 传递对应的解析选项。

2.file (.vue) is non-standard

error Parsing error: ESLint was configured to run on <tsconfigRootDir>/src/App.vue using parserOptions.project: xxxx/tsconfig.json
The extension for the file (.vue) is non-standard. You should add parserOptions.extraFileExtensions to your config
解决:
.eslintrc.cjs

"parserOptions": {
       ....
       ....
        "extraFileExtensions": ['.vue'],
    },

3.error Parsing error: '>' expected

.eslintrc.cjs

"parser": "vue-eslint-parser",

.eslintrc.cjs

module.exports = {
    "parser": "vue-eslint-parser", // 解决 Parsing error: '>' expected 报错
    "env": {
        "browser": true,
        "es2021": true
    },
    "extends": [
        "plugin:vue/vue3-essential", // vue3-base校验
        "standard-with-typescript"
    ],
    "overrides": [
        {
            "env": {
                "node": true
            },
            "files": [
                ".eslintrc.{js,cjs}"
            ],
            "parserOptions": {
                "sourceType": "script"
            }
        }
    ],
    "parserOptions": {
        "parser": "@typescript-eslint/parser",
        "project": './tsconfig.json', 
        "ecmaVersion": "latest",
        "sourceType": "module",
        "extraFileExtensions": ['.vue'],
    },
    "plugins": [
        "vue"
    ],
    "rules": {
       ......
    }
}

使用vue-eslint-parser来解析.vue文件

vue 官方提供了一个 ESLint 插件 eslint-plugin-vue,它提供了 parser 和 rules。parser 为 vue-eslint-parser,rules 为 https://eslint.vuejs.org/rules/

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容