vscode eslint+prettier配置(保存自动格式化)

本文介绍了如何在VSCode中设置Eslint和Prettier,以实现代码自动格式化。首先,需要安装Eslint、Prettier及相关依赖,然后配置.eslintrc.js、.prettierrc.js和settings.json文件。通过这些配置,可以确保在保存时自动应用代码风格规范,同时解决了Vetur与Prettier的格式化冲突问题。
摘要由CSDN通过智能技术生成

VSCode 利用 elsint 和 prettier 实现代码自动格式化

1、VScode 配置

首先需要安装 Eslint、Prettier、Vetur 插件

2、安装 Eslint 依赖(已经安装了的不必再安装)

命令: npm i -D eslint babel-eslint eslint-plugin-vue @vue/cli-plugin-eslint

eslint: ESLint 的核心代码
babel-eslint: eslint 与 babel 整合包
eslint-plugin-vue @vue/cli-plugin-eslint: eslint 与 vue 整合包

3、安装 prettier 依赖(已经安装了的不必再安装)
命令: npm i -D prettier eslint-plugin-prettier eslint-config-prettier prettier-eslint-cli

prettier:prettier 插件的核心代码
eslint-plugin-prettier:将 prettier 作为 ESLint 规范来使用
eslint-config-prettier:解决 ESLint 中的样式规范和 prettier 中样式规范的冲突,以 prettier 的样式规范为准,使 ESLint 中的样式规范自动失效
prettier-eslint-cli:prettier-eslint-cli 允许你对多个文件用 prettier-eslint 进行格式化。

4、配置 Eslint

在项目的根目录下,新建.eslintrc.js 文件,并将.eslintrc.js 里面的代码拷贝进去

5、Prettier 配置

在项目的根目录下创建.prettierrc.js 文件并将.prettierrc.js 里面的代码拷贝进去

6、setting 配置

打开 setting 将 settings.json 里面的代码黏贴进去,这样在 VScode 中保存(ctrl+s)的时候就会进行自动格式化

注意:在 vscode 中其实 Vetur 也有一套 Format 规则,因此会和 prettier 冲突。打开 setting-扩展-Vetur 将 Vetur 的规则改成 Prettier 就好了。
如果有需要忽略的文件可以在 .eslintignore 文件中进行配置

具体配置代码:
.eslintrc.js

module.exports = {
    root: true,
    parserOptions: {
      // 定义ESLint的解析器
      parser: "babel-eslint",
      sourceType: "module",
    },
    // 指定代码的运行环境
    env: {
      browser: true,
      node: true,
      es6: true,
    },
    extends: [
      //继承 vue 的标准特性
      "plugin:vue/essential",
      "eslint:recommended",
    ],
    // 自定义eslint规则,严格按照StandardJS
    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",
      // 两个空格缩进
      indent: [
        2,
        2,
        {
          SwitchCase: 1,
        },
      ],
      // 单引号
      quotes: [
        2,
        "single",
        {
          avoidEscape: true,
          allowTemplateLiterals: true,
        },
      ],
      // 未使用的变量
      "no-unused-vars": [
        2,
        {
          vars: "all",
          args: "after-used",
        },
      ],
      // 关键字前后空格
      "keyword-spacing": [
        2,
        {
          before: true,
          after: true,
        },
      ],
      // function关键字和函数名后面的空格
      "space-before-function-paren": [2, "never"],
      // 除了null,其他用===而不是==
      eqeqeq: ["error", "always", { null: "ignore" }],
      // 字符串拼接操作符直接用空格
      "space-infix-ops": 2,
      // 逗号前面不用空格,逗号后面用空格
      "comma-spacing": [
        2,
        {
          before: false,
          after: true,
        },
      ],
      // else必须和反花括号一行
      "brace-style": [
        2,
        "1tbs",
        {
          allowSingleLine: true,
        },
      ],
      // 多行 if 语句的的括号不能省
      curly: [2, "multi-line"],
      // 使用浏览器全局变量时加上 window. 前缀
      "no-undef": 2,
      // 不允许有连续多行空行
      "no-multiple-empty-lines": [
        2,
        {
          max: 1,
        },
      ],
      // 换行符在运算符的位置
      "operator-linebreak": [
        2,
        "after",
        {
          overrides: {
            "?": "before",
            ":": "before",
          },
        },
      ],
      // 条件语句中赋值语句
      "no-cond-assign": 2,
      // 单行代码块两边加空格
      "block-spacing": [2, "always"],
      // 对属性名强制使用驼峰
      camelcase: [
        0,
        {
          properties: "always",
        },
      ],
      // 不允许有多余的行末逗号
      "comma-dangle": [2, "never"],
      // 始终将逗号置于行末
      "comma-style": [2, "last"],
      // 点号操作符须与属性需在同一行
      "dot-location": [2, "property"],
      // 函数调用时标识符与括号间不留间隔
      "func-call-spacing": ["error", "never"],
      // 键值对当中冒号与值之间要留空白
      "key-spacing": [
        2,
        {
          beforeColon: false,
          afterColon: true,
        },
      ],
      // 构造函数要以大写字母开头, 但调用大写字母开头的函数不一定需要new
      "new-cap": [
        2,
        {
          newIsCap: true,
          capIsNew: false,
        },
      ],
      // 无参的构造函数调用时要带上括号
      "new-parens": 2,
      // 对象中定义了存值器,一定要对应的定义取值器
      "accessor-pairs": 2,
      // 子类的构造器中一定要调用 super
      "constructor-super": 2,
      // 使用数组字面量而不是构造器
      "no-array-constructor": "error",
      // 避免使用 arguments.callee 和 arguments.caller
      "no-caller": 2,
      // 避免对类名重新赋值
      "no-class-assign": 2,
      // 避免修改使用 const 声明的变量
      "no-const-assign": 2,
      // 正则中不要使用控制符
      "no-control-regex": "error",
      // 不要对变量使用 delete 操作。
      "no-delete-var": 2,
      // 不要定义冗余的函数参数
      "no-dupe-args": 2,
      // 类中不要定义冗余的属性
      "no-dupe-class-members": 2,
      // 对象字面量中不要定义重复的属性
      "no-dupe-keys": 2,
      // switch 语句中不要定义重复的 case 分支
      "no-duplicate-case": 2,
      // 同一模块有多个导入时一次性写完
      "no-duplicate-imports": "error",
      // 正则中不要使用空字符
      "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-new-func": "error",
      "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-sparse-arrays": 2,
      "no-template-curly-in-string": "error",
      "no-this-before-super": 2,
      "no-throw-literal": 2,
      "no-trailing-spaces": 2,
      "no-undef-init": 2,
      "no-unmodified-loop-condition": 2,
      "no-unneeded-ternary": [
        2,
        {
          defaultAssignment: false,
        },
      ],
      "no-unreachable": 2,
      "no-unsafe-finally": 2,
      "no-unsafe-negation": "error",
      "no-useless-call": 2,
      "no-useless-computed-key": 2,
      "no-useless-escape": 0,
      "no-useless-rename": 2,
      "no-whitespace-before-property": 2,
      "no-with": 2,
      "padded-blocks": [2, "never"],
      "rest-spread-spacing": ["error", "never"],
      "semi-spacing": [
        2,
        {
          before: false,
          after: true,
        },
      ],
      "space-before-blocks": [2, "always"],
      "space-in-parens": [2, "never"],
      "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"],
      // 分号
      semi: [2, "never"],
      "no-unexpected-multiline": 2,
      "arrow-spacing": [
        2,
        {
          before: true,
          after: true,
        },
      ],
      "eol-last": 2,
      "generator-star-spacing": [
        2,
        {
          before: true,
          after: true,
        },
      ],
      "handle-callback-err": [2, "^(err|error)$"],
      "jsx-quotes": [2, "prefer-single"],
      "no-array-constructor": 2,
      "no-console": "off",
      "no-native-reassign": 2,
      "no-negated-in-lhs": 2,
      "no-shadow-restricted-names": 2,
      "no-spaced-func": 2,
      "no-useless-constructor": 2,
      "one-var": [
        2,
        {
          initialized: "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"],
    },
    //当使用第三方的SDK时,eslint会报找不到,可以加入到globals,取消对这个的检查
    globals: {
      fengmap: true,
    },
  };

.prettierrc.js

module.exports = {
    // 最大长度80个字符
    printWidth: 80,
    // 行末分号
    semi: false,
    // 单引号
    singleQuote: true,
    // JSX双引号
    jsxSingleQuote: false,
    // 尽可能使用尾随逗号(包括函数参数)
    trailingComma: "none",
    // 在对象文字中打印括号之间的空格。
    bracketSpacing: true,
    // > 标签放在最后一行的末尾,而不是单独放在下一行
    jsxBracketSameLine: false,
    // 箭头圆括号
    arrowParens: "avoid",
    // 在文件顶部插入一个特殊的 @format 标记,指定文件格式需要被格式化。
    insertPragma: false,
    // 缩进
    tabWidth: 2,
    // 使用tab还是空格
    useTabs: false,
    // 行尾换行格式
    endOfLine: "auto",
    HTMLWhitespaceSensitivity: "ignore",
    extends: [
        //继承 vue 的标准特性
        "plugin:vue/essential",
        "eslint:recommended",
        //避免与 prettier 冲突
        "plugin:prettier/recommended",
      ]
  };

settings.json

{
    "workbench.colorTheme": "One Dark Pro",
    "eslint.enable": true,
    "eslint.options": {
      "extensions": [".js", ".vue", ".ts", ".tsx"]
    },
    "editor.formatOnSave": true,
    "editor.codeActionsOnSave": {
      "source.fixAll.eslint": true
    },
    "eslint.validate": [
      "vue",
      "html",
      "javascript",
      "typescript",
      "javascriptreact",
      "typescriptreact"
    ],
    "vetur.format.defaultFormatter.html": "prettier"
  }

注意:在 vscode 中其实 Vetur 也有一套 Format 规则,因此会和 prettier 冲突。打开 setting-扩展-Vetur 将 Vetur 的规则改成 Prettier 就好了。

  • 12
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 13
    评论
### 回答1: VSCode是一款流行的代码编辑器,可以通过安装插件来集成ESLintPrettierESLint是一款JavaScript代码检查工具,可以帮助开发者发现代码中的错误和潜在问题。Prettier是一款代码格式化工具,可以自动格式化代码,使其更易于阅读和维护。配置ESLintPrettier可以帮助开发者在编写代码时更加高效和准确。 ### 回答2: 近年来,前端工具生态系统飞快的发展,其中强化代码风格和静态代码质量的工具是越来越重要的,而比较流行和实用的两个工具是ESLintPrettier,它们都被广泛应用于JavaScript和TypeScript项目中。 VS Code是一款流行的编辑器,它与ESLintPrettier紧密集成,并允许我们在编辑器中对它们进行配置。这个配置可以让我们轻松地实现自动修复代码风格和语法错误,并确保格式一致性,从而提高代码质量和可读性。 首先,我们需要在项目中安装ESLintPrettier。我们可以在 package.json 中的 devDependencies 中添加以下两个依赖: ``` "eslint": "^7.31.0", "prettier": "^2.4.1" ``` 接下来,我们需要安装两个 VS Code 扩展程序进行配置: - ESLint扩展程序:https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint - Prettier扩展程序:https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode 当完成上述操作后,我们可以在 VS Code 中的设置中打开 ESLint 配置,通过以下方式启用 ESLint: ``` { "editor.formatOnSave": false, "editor.codeActionsOnSave": { "source.fixAll.eslint": true }, "eslint.validate": [ "javascript", "javascriptreact", "typescript", "typescriptreact" ] } ``` 这个配置的意义是,当保存文件时,自动修复 ESLint 指出的错误和警告,同时,在实时代码检查时支持 JavaScript 和 TypeScript 语言和相关的文件扩展。 接下来,我们可以配置 Prettier 执行格式化操作。为了让 PrettierESLint 集成,我们可以添加一个 `.prettierrc` 文件到项目的根目录下: ``` { "singleQuote": true, "trailingComma": "all", "tabWidth": 2 } ``` 这里只配置了三个 Prettier 的选项,其余的选项可以根据具体需求进行更改。关于 Prettier 的具体选项,可以查看官方文档:https://prettier.io/docs/en/options.html 最后,在 VS Code 中的设置中,我们需要添加以下配置: ``` { "editor.defaultFormatter": "esbenp.prettier-vscode", "[javascript]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[javascriptreact]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[typescript]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[typescriptreact]": { "editor.defaultFormatter": "esbenp.prettier-vscode" } } ``` 这个配置告诉 VS Code,在 JavaScript 和 TypeScript 语言的文件中,默认使用 Prettier 进行格式化。 综上所述,通过以上的配置,我们可以在 VS Code 中实现对 ESLintPrettier自动检测和代码格式化。这样,我们可以有效地提高代码的可读性、可维护性和质量,同时也能提高我们的开发效率和团队协作效率。 ### 回答3: VSCode是一款非常流行的代码编辑器,目前市场占有率已经超过了其他编辑器。同时,VSCode也支持各种插件和配置,可以帮助开发者更高效地编写代码。其中,ESLintPrettier是两款比较常见的插件,也是必不可少的。下面我们来讲一下如何在VSCode配置ESLintPrettier。 1. 安装ESLintPrettier插件 首先,需要在VSCode的插件市场中搜索并安装ESLintPrettier插件。安装完成后,需要重新启动VSCode才能生效。 2. 配置ESLintVSCode中按下Ctrl+Shift+P,打开命令面板,然后输入“Open Workspace Settings”打开VSCode的设置。找到ESLint配置项,并进行配置。这里可以选择使用默认配置,也可以按自己需要进行定制化配置。 3. 配置Prettier 同样地,在命令面板中输入“Open Workspace Settings”打开VSCode的设置,找到Prettier配置项,并进行配置。这里同样可以选择默认配置或按自己需求进行配置。 4. 同步ESLintPrettier配置 配置完成后,需要同步ESLintPrettier配置,以确保代码的风格一致。需要安装一个名为“eslint-plugin-prettier”的插件,然后在.eslintrc文件中进行配置。 以上就是在VSCode配置ESLintPrettier的方法。配置完成后,可以在代码编写过程中更加高效和规范。
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱喝冰可乐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值