ESLint和Prettier结合「高亮显示不规范代码」「保存时自动规范代码」

20,402 阅读3分钟

ESLint简介

直接上官网:链接

再来一张翻译过后的图片 [考虑到有小伙伴会要翻译插件,推荐一下翻译软件:彩云小译]

WX20210909-172002.png

Prettier简介

直接上官网:链接

再来一张翻译过后的图片 [考虑到有小伙伴会要翻译插件,推荐一下翻译软件:彩云小译]

WX20210909-173135.png

使用

以我现在公司的项目为例技术栈:vue.js+nuxt.js+egg.js

配置比较简单,具体步骤如下:

1、安装依赖

npm install babel-eslint eslint eslint-config-prettier eslint-loader eslint-plugin-vue eslint-plugin-prettier prettier --save-dev 

2、添加配置文件 .eslintrc.js 文件:

module.exports = {
  root: true,
  extends: [
    "eslint:recommended",
    "plugin:vue/recommended",
    "plugin:prettier/recommended",
  ],
  env: {
    browser: true,
    node: true,
  },
  plugins: ["vue"],
  parserOptions: {
    parser: "babel-eslint",
    sourceType: "module",
    allowImportExportEverywhere: false,
    codeFrame: false,
  },
  rules: {
    "no-param-reassign": 0,
    "max-len": [
      2,
      {
        code: 140,
        ignoreStrings: true,
        ignoreTemplateLiterals: true,
        ignoreRegExpLiterals: true,
        ignorePattern: "data:image",
      },
    ],
    "no-plusplus": 0,
    "vue/html-self-closing": 0,
    "comma-dangle": 0,
    "vue/require-default-prop": 0,
    "no-underscore-dangle": 0,
    "no-unused-expressions": 0,
    "array-callback-return": 0,
    "global-require": 0,
    radix: 0,
    "no-console": 0,
    "consistent-return": 1,
    "class-methods-use-this": 0,
    "no-buffer-constructor": 1,
    "no-continue": 0,
    camelcase: 0,
    "vue/attributes-order": 0,
    "no-use-before-define": ["error", { functions: false, classes: false }],
    "no-debugger": 0,
    "vue/attribute-hyphenation": 0,
    "vue/no-use-v-if-with-v-for": 0,
    "no-multiple-empty-lines": 0,
    strict: 0,
    "lines-between-class-members": 0,
    "operator-linebreak": 0,
    "no-else-return": 0,
    "vue/no-mutating-props": 0,
    "vue/require-prop-type-constructor": 0,
    "vue/return-in-computed-property": 0,
    "object-curly-newline": 0,
    "operator-assignment": 0,
    "vue/no-unused-components": 0,
    "vue/max-attributes-per-line": [
      "error",
      {
        singleline: 3,
        multiline: {
          max: 3,
          allowFirstLine: true,
        },
      },
    ],
  },
  globals: {
    __NUXT__: true,
  },
};

到此其实就配置完了,但还是补充几个好用的配置:

1、一个更爽的配置,可查看整个项目不符合ESLint配置的所有文件,并且可以一次性修改所有不符合ESLint配置的文件。

  #在 package.json 文件中添加 checklint 和 reviselint 命令
  "scripts": {
    "checklint": "eslint --ext .js,.vue --ignore-path .gitignore .",
    "reviselint": "eslint --fix --ext .js,.vue --ignore-path .gitignore ."
  },
npm run checklint // 查看项目中的不规范

npm run reviselint // 修改项目中的不规范

2、最后如何动态的去检查代码的规范问题,这个我们只需要在配置文件 nuxt.config.js 中加入下面的配置就能在每次保存的时候在控制台或者打开项目的浏览器内看到那些代码不符合规范。

 build: {
   extend(config, ctx) {
      // Run ESLint on save
      if (ctx.isDev && ctx.isClient) {
        config.module.rules.push({
          enforce: "pre",
          test: /\.(js|vue)$/,
          loader: "eslint-loader",
          exclude: /(node_modules)/
        })
      }
    }
  }

3、在VScode中,编写代码时有不规范的地方高亮显示出来并且在 Ctrl+S 保存的时候自动格式化为规范的代码,这个也是我觉得比较爽的操作,不用一个一个地方去改。

这个需要配合插件来完成 在vscode中添加eslint和vetur插件:

image.png

image.png

安装完插件以后最好重启一个VScode, 然后你就能看到项目中不符合你定义规范的代码就会高亮出来,如图:

image.png

最后也是最爽的地方,配置 Ctrl+S 保存的时候自动规范化代码

  • 找到 code => 首选项 => 设置 => settings.json 文件
  • 然后对 settings.json 文件进行修改
  • 下面是我的 settings.json 文件 可以参考一下
{
    "workbench.iconTheme": "vscode-icons",
    "vsicons.associations.fileDefault.file_light": null,
    "editor.codeActionsOnSave": {
        "source.fixAll.eslint": true
    },
    "files.associations": {
        "*.vue": "vue"
    },
    "explorer.confirmDelete": false,
    "terminal.integrated.automationShell.osx": "",

    // tab 大小为2个空格
    "editor.tabSize": 2,
    "eslint.autoFixOnSave": true,
    "eslint.options": {
        "extensions": [
            ".js",
            ".vue"
        ]
    },
    "eslint.validate": [
        "javascript",
        {
            "language": "vue",
            "autoFix": true
        },
        "html",
        "vue"
    ],
    // // 保存时格式化
    "editor.formatOnSave": false,
    // // 开启 vscode 文件路径导航
    "breadcrumbs.enabled": true,
    //  显示 markdown 中英文切换时产生的特殊字符
    "editor.renderControlCharacters": true,
    // eslint 检测文件类型
    "vetur.format.defaultFormatter.html": "prettyhtml",
    "vetur.format.defaultFormatterOptions": {
        "js-beautify-html": {
        "wrap_attributes": "auto"
        },
        "prettyhtml": {
        "printWidth": 200,
        "singleQuote": false,
        "wrapAttributes": false,
        "sortAttributes": false
        },
        "prettier": {
        "semi": false,
        "singleQuote": true
        }
    },
    "extensions.confirmedUriHandlerExtensionIds": [],
    "fileheader.configObj": {
        "createFileTime": true,
        "language": {
            "languagetest": {
                "head": "/$$",
                "middle": " $ @",
                "end": " $/"
            }
        },
        "autoAdd": true,
        "autoAddLine": 100,
        "autoAlready": true,
        "annotationStr": {
            "head": "/*",
            "middle": " * @",
            "end": " */",
            "use": false
        },
        "headInsertLine": {
            "php": 2,
            "sh": 2
        },
        "beforeAnnotation": {
            "文件后缀": "该文件后缀的头部注释之前添加某些内容"
        },
        "afterAnnotation": {
            "文件后缀": "该文件后缀的头部注释之后添加某些内容"
        },
        "specialOptions": {
            "特殊字段": "自定义比如LastEditTime/LastEditors"
        },
        "switch": {
            "newlineAddAnnotation": true
        },
        "supportAutoLanguage": [],
        "prohibitAutoAdd": [
            "json"
        ],
        "folderBlacklist": [
            "node_modules",
            "文件夹禁止自动添加头部注释"
        ],
        "prohibitItemAutoAdd": [
            "项目的全称, 整个项目禁止自动添加头部注释, 可以使用快捷键添加"
        ],
        "moveCursor": true,
        "dateFormat": "YYYY-MM-DD HH:mm:ss",
        "atSymbol": [
            "@",
            "@"
        ],
        "atSymbolObj": {
            "文件后缀": [
                "头部注释@符号",
                "函数注释@符号"
            ]
        },
        "colon": [
            ": ",
            ": "
        ],
        "colonObj": {
            "文件后缀": [
                "头部注释冒号",
                "函数注释冒号"
            ]
        },
        "filePathColon": "路径分隔符替换",
        "showErrorMessage": false,
        "writeLog": false,
        "wideSame": false,
        "wideNum": 13,
        "functionWideNum": 0,
        "CheckFileChange": false,
        "createHeader": true,
        "useWorker": false,
        "designAddHead": false,
        "headDesignName": "random",
        "headDesign": false,
        "cursorModeInternal": false,
        "openFunctionParamsCheck": true
    },
    // 文件头部注释
    "fileheader.customMade": {
        "Descripttion":"",
        "version":"1.0.0",
        "Author":"ningdezheng@meishubao.com",
        "Date":"Do not edit", // 不需要设置,按下快捷键后自动生成
        "LastEditors":"ningdezheng@meishubao.com",
        "LastEditTime":"Do not Edit"// 不需要设置,按下快捷键后自动生成
    },
    //函数注释
    "fileheader.cursorMode": {
        "msg":"",
    },
    "json.schemas": [],
    "explorer.confirmDragAndDrop": false,
    "workbench.editor.enablePreview": false,
    "window.zoomLevel": 1,
    "gitlens.gitCommands.skipConfirmations": [
        "fetch:command",
        "switch:command"
    ],
    "vsicons.dontShowNewVersionMessage": true,
    "leetcode.endpoint": "leetcode-cn",
    "leetcode.workspaceFolder": "/Users/admin/.leetcode",
    "leetcode.defaultLanguage": "javascript",
    "leetcode.hint.configWebviewMarkdown": false,
    "leetcode.hint.commentDescription": false,
    "leetcode.hint.commandShortcut": false,
    "cSpell.language": "en,en-US",
    "cSpell.enableFiletypes": [
        "vue",
        "vue-sugarss"
    ],
}

然后回到上面的文件,进入文件中,只需要 Ctrl+S 保存一下,代码自动格式化,如图:

image.png 快捷方便!一个字:爽~

建议

如果你对你的代码有严格的代码洁癖或者你对你的团队有必须的代码书写规范,两者结合将会是你的代码管理起来更加方便和优雅。

还有任何东西想要熟练地使用第一点我觉得都需要认真的看一遍文档(api),这样才能让你更好的去理解他。