vue项目eslint配置

一,官网地址

https://cn.eslint.org/docs/user-guide/getting-started

二,配置eslint

1,安装

npm install eslint --save-dev

2,生成.eslintrc文件

在项目根目录运行:

./node_modules/.bin/eslint --init

当然,这句命令行可以使用这个代替,达到的效果是一样的,按照提示选择自己需要的配置,就可以在根目录生成一个.eslintrc的文件。

npx eslint --init

在这里插入图片描述

3,生成的.eslintrc文件

这时候,会启用默认的eslint配置,如果想要自定义配置,可以修改.eslintrc文件的内容。

module.exports = {
    "env": {
        "browser": true,
        "es6": true,
        "node": true
    },
    "extends": [
        "eslint:recommended",
        "plugin:vue/essential"
    ],
    "globals": {
        "Atomics": "readonly",
        "SharedArrayBuffer": "readonly"
    },
    "parserOptions": {
        "parser": "babel-eslint", // 解析器,默认使用Espree
        "ecmaVersion": 2018,  //支持es2018语法
        "sourceType": "module",// 指定来源的类型,"script" (默认) 或 "module"(如果你的代码是 ECMAScript 模块)
    },
    "plugins": [
        "vue",
        'prettier'
    ],
    "rules": {
    //这里写你想要自定义的规则
    }
};

4,package.json文件

当安装eslint之后,这个文件中会有这么一段配置:
在这里插入图片描述
root:true,默认情况下,ESLint 会在所有父级目录里寻找配置文件,一直到根目录。如果发现配置文件中有 “root”: true,它就会停止在父级目录中寻找。

三,.eslintrc文件的结构

1,想启用eslint的环境

"env": {
        "browser": true,
        "es6": true,
        "node": true
    },//想启用eslint的环境

2,启用推荐的规则

所有的规则默认都是禁用的。在配置文件中,使用 “extends”: “eslint:recommended” 来启用推荐的规则,报告一些常见的问题,在下文中这些推荐的规则都带有一个标记。具体查看https://cn.eslint.org/docs/rules/

    "extends": [
        "eslint:recommended",
        "plugin:vue/essential"
    ],

3,parserOptions额外的配置

"parserOptions": {
        "parser": "babel-eslint", // 解析器,默认使用Espree
        "ecmaVersion": 2018,  //支持es2018语法
        "sourceType": "module",// 指定来源的类型,"script" (默认) 或 "module"(如果你的代码是 ECMAScript 模块)
        // 使用的额外的语言特性
        "ecmaFeatures": {
            "jsx": true, // 启用 JSX
            "globalReturn": true, // 允许在全局作用域下使用 return 语句
            "impliedStrict": true, // 启用全局 strict mode (如果 ecmaVersion 是 5 或更高)
            "experimentalObjectRestSpread": true,	// 启用实验性的 object rest/spread properties 支持。(重要:这是一个实验性的功能,在未来可能会有明显改变。 建议你写的规则 不要 依赖该功能,除非当它发生改变时你愿意承担维护成本。)
        }
    },

4,plugins

ESLint 支持使用第三方插件。在使用插件之前,你必须使用 npm 安装它。
在配置文件里配置插件时,可以使用 plugins 关键字来存放插件名字的列表。插件名称可以省略 eslint-plugin- 前缀。

    "plugins": [
        "vue",
        'prettier'
    ],

5,rules

ESLint 附带有大量的规则。你可以使用注释或配置文件修改你项目中要使用的规则。要改变一个规则设置,你必须将规则 ID 设置为下列值之一:

"off"0 - 关闭规则
"warn"1 - 开启规则,使用警告级别的错误:warn (不会导致程序退出)
"error"2 - 开启规则,使用错误级别的错误:error (当被触发的时候,程序会退出)

例如强制分号结尾,强制双引号:

    "rules": {
        "quotes": [1, "double"],
        semi: [
            2,
            'always',
            {
              omitLastInOneLineBlock: true
            }
          ],
    }

于是单引号就会警告,按ctrl+s保存,就会变成双引号:
在这里插入图片描述

四,我项目中的eslint规则配置

module.exports = {
  "env": {
    "browser": true,
    "es6": true,
    "node": true
  }, //想启用eslint的环境
  "extends": [
    // "eslint:recommended",//不启用默认配置,而是自定义规则
    "plugin:vue/essential"
  ],
  "globals": {
    "Atomics": "readonly",
    "SharedArrayBuffer": "readonly"
  },
  "parserOptions": {
    "parser": "babel-eslint", // 解析器,默认使用Espree
    "ecmaVersion": 2018,  //支持es2018语法
    "sourceType": "module", // 指定来源的类型,"script" (默认) 或 "module"(如果你的代码是 ECMAScript 模块)
    // 使用的额外的语言特性
    "ecmaFeatures": {
      "jsx": true, // 启用 JSX
      "globalReturn": true, // 允许在全局作用域下使用 return 语句
      "impliedStrict": true, // 启用全局 strict mode (如果 ecmaVersion 是 5 或更高)
      "experimentalObjectRestSpread": true	// 启用实验性的 object rest/spread properties 支持。(重要:这是一个实验性的功能,在未来可能会有明显改变。 建议你写的规则 不要 依赖该功能,除非当它发生改变时你愿意承担维护成本。)
    }
  },
  "plugins": [
    "vue",
    "prettier"
  ],
  "rules": {
    "quotes": [1, "double"], //警告,必须双引号
    "no-compare-neg-zero": 2, //禁止与 -0 进行比较
    "no-cond-assign": [
      2,
      "except-parens"
    ], //禁止条件语句中出现赋值操作符
    "no-console": 0, //允许出现console
    "no-constant-condition": 2, //禁止在条件中使用常量表达式
    "no-control-regex": 2, //禁止在正则表达式中使用控制字符
    "no-debugger": 0, //可以使用debugger
    "no-dupe-args": 2, //禁止 function 定义中出现重名参数
    "no-dupe-keys": 2, //禁止对象字面量中出现重复的 key
    "no-duplicate-case": 2, //禁止出现重复的 case 标签
    "no-empty": 2, //禁止出现空语句块
    "no-empty-character-class": 2, //禁止在正则表达式中使用空字符集
    "no-ex-assign": 2, //禁止对 catch 子句的参数重新赋值
    "no-extra-boolean-cast": 2, //禁止不必要的布尔转换
    "no-extra-parens": [
      "error",
      "functions"
    ], //禁止不必要的括号
    "no-extra-semi": 2, //禁止不必要的分号
    "no-func-assign": 2, //禁止对 function 声明重新赋值
    "no-inner-declarations": 0, //禁止在嵌套的块中出现变量声明或 function 声明
    "no-invalid-regexp": 2, //禁止 RegExp 构造函数中存在无效的正则表达式字符串
    "no-irregular-whitespace": 2, //禁止不规则的空白
    "no-obj-calls": 2, //禁止把全局对象作为函数调用
    "no-prototype-builtins": 2, //禁止直接调用 Object.prototypes 的内置属性
    "no-regex-spaces": 2, //禁止正则表达式字面量中出现多个空格
    "no-sparse-arrays": 2, //禁用稀疏数组
    "no-template-curly-in-string": 0, //禁止在常规字符串中出现模板字面量占位符语法
    "no-unexpected-multiline": 2, //禁止出现令人困惑的多行表达式
    "no-unreachable": 2, //禁止在 return、throw、continue 和 break 语句之后出现不可达代码
    "no-unsafe-finally": 2, //禁止在 finally 语句块中出现控制流语句
    "no-unsafe-negation": 2, //禁止对关系运算符的左操作数使用否定操作符
    "use-isnan": 2, //要求使用 isNaN() 检查 NaN
    "valid-jsdoc": "off", //
    "valid-typeof": 2, //强制 typeof 表达式与有效的字符串进行比较

    "curly": 2, //强制所有控制语句使用一致的括号风格
    "consistent-return": [
      2,
      {
        treatUndefinedAsUnspecified: true
      }
    ],
    "default-case": 2,
    eqeqeq: "off",
    "guard-for-in": 0,
    "no-case-declarations": 0,
    "no-empty-pattern": 2,
    "no-fallthrough": 2,
    "no-global-assign": [
      2,
      {
        exceptions: []
      }
    ],
    "no-octal": 2,
    "no-redeclare": 2,
    "no-self-assign": 2,
    "no-unused-labels": 2,
    "no-useless-escape": 2,
      
    strict: 2,
      
    "no-delete-var": 2,
    "no-undefined": 0,
    "no-undef": 2,
    "no-use-before-define": 2,
      
    "array-bracket-spacing": [
      2,
      "never"
    ],
    "block-spacing": [
      2,
      "always"
    ],
    "brace-style": [
      2,
      "1tbs"
    ],
    "comma-dangle": [
      "error",
      "never"
    ],
    "comma-spacing": [
      2,
      {
        before: false,
        after: true
      }
    ],
    "comma-style": [
      2,
      "last"
    ],
    "computed-property-spacing": [
      "error",
      "never"
    ],
    "eol-last": [
      2,
      "always"
    ],
    "func-call-spacing": [
      "error",
      "never"
    ],
    indent: [
      "error",
      2,
      {
        SwitchCase: 1
      }
    ],
    "jsx-quotes": [
      "error",
      "prefer-double"
    ],
    "key-spacing": [
      "error",
      {
        beforeColon: false,
        afterColon: true
      }
    ],
    "new-cap": [
      "error",
      {
        newIsCap: true,
        capIsNewExceptionPattern: "(Type[a-zA-Z0-9]+|Deco[a-zA-Z0-9]+)+"
      }
    ],
    "new-parens": "error",
    "no-mixed-spaces-and-tabs": 2,
    "no-multi-assign": "error",
    "no-multiple-empty-lines": "error",
      
      
    semi: [
      2,
      "always",
      {
        omitLastInOneLineBlock: true
      }
    ],
      
    "constructor-super": 2,
    "no-class-assign": 0,
    "no-const-assign": 2,
    "no-this-before-super": 2,
    "no-var": 2,
    "no-dupe-class-members": 2,
    "no-new-symbol": 2,
    "require-yield": 2,
    "prefer-const": 0
  }
};

五,配置完成后检查文件

npm run lint

在这里插入图片描述
如果发生报错了。查看对应的报错提醒,完成修改即可。

六,配合prettier

https://blog.csdn.net/liule18235434869/article/details/103468836/

七,我的使用

为了避免eslint和pritter冲突,最好vscode中的配置文件和这两者应该一致。

eslint:

module.exports = {
  "env": {
    "browser": true,
    "es6": true,
    "node": true
  }, //想启用eslint的环境
  "extends": [
    // "eslint:recommended",//不启用默认配置,而是自定义规则
    "plugin:vue/essential",
    "@vue/prettier"//配合prettier,需要放在extends最后一个
  ],
  "globals": {
    "Atomics": "readonly",
    "SharedArrayBuffer": "readonly"
  },
  "parserOptions": {
    "parser": "babel-eslint", // 解析器,默认使用Espree
    "ecmaVersion": 2018,  //支持es2018语法
    "sourceType": "module", // 指定来源的类型,"script" (默认) 或 "module"(如果你的代码是 ECMAScript 模块)
    // 使用的额外的语言特性
    "ecmaFeatures": {
      "jsx": true, // 启用 JSX
      "globalReturn": true, // 允许在全局作用域下使用 return 语句
      "impliedStrict": true, // 启用全局 strict mode (如果 ecmaVersion 是 5 或更高)
      "experimentalObjectRestSpread": true	// 启用实验性的 object rest/spread properties 支持。(重要:这是一个实验性的功能,在未来可能会有明显改变。 建议你写的规则 不要 依赖该功能,除非当它发生改变时你愿意承担维护成本。)
    }
  },
  "plugins": [
    "vue",
    "prettier"
  ],
  "rules": {
    "quotes": [1, "double"], //警告,必须双引号
    "no-compare-neg-zero": 2, //禁止与 -0 进行比较
    "no-cond-assign": [
      2,
      "except-parens"
    ], //禁止条件语句中出现赋值操作符
    "no-console": 0, //允许出现console
    "no-constant-condition": 2, //禁止在条件中使用常量表达式
    "no-control-regex": 2, //禁止在正则表达式中使用控制字符
    "no-debugger": 0, //可以使用debugger
    "no-dupe-args": 2, //禁止 function 定义中出现重名参数
    "no-dupe-keys": 2, //禁止对象字面量中出现重复的 key
    "no-duplicate-case": 2, //禁止出现重复的 case 标签
    "no-empty": 2, //禁止出现空语句块
    "no-empty-character-class": 2, //禁止在正则表达式中使用空字符集
    "no-ex-assign": 2, //禁止对 catch 子句的参数重新赋值
    "no-extra-boolean-cast": 2, //禁止不必要的布尔转换
    "no-extra-parens": [
      "error",
      "functions"
    ], //禁止不必要的括号
    "no-extra-semi": 2, //禁止不必要的分号
    "no-func-assign": 2, //禁止对 function 声明重新赋值
    "no-inner-declarations": 0, //禁止在嵌套的块中出现变量声明或 function 声明
    "no-invalid-regexp": 2, //禁止 RegExp 构造函数中存在无效的正则表达式字符串
    "no-irregular-whitespace": 2, //禁止不规则的空白
    "no-obj-calls": 2, //禁止把全局对象作为函数调用
    "no-prototype-builtins": 2, //禁止直接调用 Object.prototypes 的内置属性
    "no-regex-spaces": 2, //禁止正则表达式字面量中出现多个空格
    "no-sparse-arrays": 2, //禁用稀疏数组
    "no-template-curly-in-string": 0, //禁止在常规字符串中出现模板字面量占位符语法
    "no-unexpected-multiline": 2, //禁止出现令人困惑的多行表达式
    "no-unreachable": 2, //禁止在 return、throw、continue 和 break 语句之后出现不可达代码
    "no-unsafe-finally": 2, //禁止在 finally 语句块中出现控制流语句
    "no-unsafe-negation": 2, //禁止对关系运算符的左操作数使用否定操作符
    "use-isnan": 2, //要求使用 isNaN() 检查 NaN
    "valid-jsdoc": "off", //
    "valid-typeof": 2, //强制 typeof 表达式与有效的字符串进行比较

    "curly": 2, //强制所有控制语句使用一致的括号风格
    "consistent-return": [
      2,
      {
        treatUndefinedAsUnspecified: true
      }
    ],
    "default-case": 2,
    eqeqeq: "off",
    "guard-for-in": 0,
    "no-case-declarations": 0,
    "no-empty-pattern": 2,
    "no-fallthrough": 2,
    "no-global-assign": [
      2,
      {
        exceptions: []
      }
    ],
    "no-octal": 2,
    "no-redeclare": 2,
    "no-self-assign": 2,
    "no-unused-labels": 2,
    "no-useless-escape": 2,
      
    strict: 2,
      
    "no-delete-var": 2,
    "no-undefined": 0,
    "no-undef": 2,
    "no-use-before-define": 2,
      
    "array-bracket-spacing": [
      2,
      "never"
    ],
    "block-spacing": [
      2,
      "always"
    ],
    "brace-style": [
      2,
      "1tbs"
    ],
    "comma-dangle": [
      "error",
      "never"
    ],
    "comma-spacing": [
      2,
      {
        before: false,
        after: true
      }
    ],
    "comma-style": [
      2,
      "last"
    ],
    "computed-property-spacing": [
      "error",
      "never"
    ],
    "eol-last": [
      2,
      "always"
    ],
    "func-call-spacing": [
      "error",
      "never"
    ],
    indent: [
      "error",
      2,
      {
        SwitchCase: 1
      }
    ],
    "jsx-quotes": [
      "error",
      "prefer-double"
    ],
    "key-spacing": [
      "error",
      {
        beforeColon: false,
        afterColon: true
      }
    ],
    "new-cap": [
      "error",
      {
        newIsCap: true,
        capIsNewExceptionPattern: "(Type[a-zA-Z0-9]+|Deco[a-zA-Z0-9]+)+"
      }
    ],
    "new-parens": "error",
    "no-mixed-spaces-and-tabs": 2,
    "no-multi-assign": "error",
    "no-multiple-empty-lines": "error",
      
      
    semi: [
      2,
      "always",
      {
        omitLastInOneLineBlock: true
      }
    ],
      
    "constructor-super": 2,
    "no-class-assign": 0,
    "no-const-assign": 2,
    "no-this-before-super": 2,
    "no-var": 2,
    "no-dupe-class-members": 2,
    "no-new-symbol": 2,
    "require-yield": 2,
    "prefer-const": 0,
    
    "prettier/prettier": "error"
  }
};

prettier

{
  "arrowParens": "avoid",
  "bracketSpacing": true,
  "cursorOffset": -1,
  "insertPragma": false,
  "jsxBracketSameLine": false,
  "plugins": [],
  "printWidth": 80,
  "proseWrap": "preserve",
  "rangeStart": 0,
  "requirePragma": false,
  "semi": true,
  "singleQuote": false,
  "tabWidth": 2,
  "trailingComma": "none",
  "useTabs": false
}

vscode的package.json

{
    "editor.minimap.enabled": false,
    "window.menuBarVisibility": "default",
    "diffEditor.ignoreTrimWhitespace": false,
    "javascript.updateImportsOnFileMove.enabled": "always",
    "http.proxyAuthorization": "false",
    "workbench.editor.enablePreview": false,
    "workbench.startupEditor": "newUntitledFile",
    "emmet.extensionsPath": "",
    "emmet.includeLanguages": {
        "vue-html": "html",
        "vue": "html"
    },
    "emmet.preferences": {
    
    },
    "emmet.showSuggestionsAsSnippets": true,
    "eslint.codeAction.showDocumentation": {
        "enable": true
    },
    //配置保存时按照eslint文件的规则来处理一下代码
    "editor.codeActionsOnSave": {
        "source.fixAll.eslint": true,
        "eslint.autoFixOnSave" : true,
    },
    //配置eslint适用于vue代码
    "eslint.validate": [
        "vue",
        "javascript",
        // "typescript",
        // "typescriptreact",
        // "html",
        // {
        //     "language":"vue",
        //     "autoFix":true
        // }
    ],
    "window.zoomLevel": -1,
    "leek-fund.immersiveBackground": true,
    "leek-fund.statusBarStock": [
        "sh000001"
    ],
    "interview.workspaceFolder": "C:\\Users\\10594\\.FEInterview",
    "eslint.codeActionsOnSave.mode": "problems",
    "eslint.format.enable": true,
    "interview.updateNotification": true,
    "leek-fund.fundSort": -1,
    "leek-fund.funds": [
        "008888",
        "008087",
        "161725",
        "006600",
        "163115",
        "001576",
        "160225",
        "519674",
        "005311"
    ],
    "leek-fund.showEarnings": 0,
    
    // 使能每一种语言默认格式化规则
    "[html]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[css]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[less]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[vue]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[javascript]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[typescriptreact]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },

    "javascript.validate.enable": true,
    "emmet.excludeLanguages": [
        "markdown"
    ],
    /*  prettier的配置 */
    "prettier.printWidth": 80, // 超过最大值换行
    "prettier.tabWidth": 2, // 缩进字节数
    "prettier.useTabs": false, // 句尾添加分号
    "prettier.singleQuote": false, // 使用单引号代替双引号
    "prettier.proseWrap": "preserve", //  (x) => {} 箭头函数参数只有一个时是否要有小括号。avoid:省略括号
    "prettier.bracketSpacing": true, // 在对象,数组括号与文字之间加空格 "{ foo: bar }"
    "prettier.disableLanguages": ["vue"], // 不格式化vue文件,vue文件的格式化单独设置
    "prettier.endOfLine": "auto", // 结尾是 \n \r \n\r auto
    "prettier.eslintIntegration": false, //不让prettier使用eslint的代码格式进行校验
    "prettier.htmlWhitespaceSensitivity": "ignore",
    "prettier.ignorePath": ".prettierignore", // 不使用prettier格式化的文件填写在项目的.prettierignore文件中
    "prettier.jsxBracketSameLine": false, // 在jsx中把'>' 是否单独放一行
    "prettier.jsxSingleQuote": false, // 在jsx中使用单引号代替双引号
    "prettier.parser": "babylon", // 格式化的解析器,默认是babylon
    "prettier.requireConfig": false, // Require a 'prettierconfig' to format prettier
    "prettier.stylelintIntegration": false, //不让prettier使用stylelint的代码格式进行校验
    "prettier.trailingComma": "none", // 在对象或数组最后一个元素后面是否加逗号(在ES5中加尾逗号)
    "prettier.tslintIntegration": false,
    "[jsonc]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[typescript]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[json]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[javascriptreact]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    }, // 不让prettier使用tslint的代码格式进行校验
    "vetur.experimental.templateInterpolationService": false,
    "vetur.ignoreProjectWarning": true,
    "prettier.arrowParens": "avoid"
}

八,校验及修复所有文件

  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "test": "vue-cli-service build --mode testing",
    "lint": "vue-cli-service lint",
    "lint-fix": "eslint --fix --ext .js,.vue src"
  },

于是:

npm run lint 
npm run lint-fix
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值