ESLint profile

Go directly to the official website: link

Here is another picture after translation. [Considering that some friends need translation plug-in, I recommend the translation software: Caiyun Xiaoyi]

Prettier profile

Go directly to the official website: link

Here is another picture after translation. [Considering that some friends need translation plug-in, I recommend the translation software: Caiyun Xiaoyi]

use

Take the project of my current company as an example: vue. Js +nuxt.js+egg.js

The configuration is simple as follows:

1. Install dependencies

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

2, add configuration file.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,}};Copy the code

This is the end of the configuration, but there are a few useful configurations:

1. For a better configuration, you can view all files that do not comply with ESLint configuration for the entire project and modify all files that do not comply with ESLint configuration at once.

# Add checklint and Reviselint commands to package.json file"scripts": {
    "checklint": "eslint --ext .js,.vue --ignore-path .gitignore ."."reviselint": "eslint --fix --ext .js,.vue --ignore-path .gitignore ."
  },
Copy the code
npm run checklint // Check for irregularities in the project

npm run reviselint // Fix a non-specification in the project
Copy the code

2. Finally, how to dynamically check the code for specification problems? We only need to add the following configuration file in nuxt.config.js to see that the code does not conform to the specification in the console or open the browser of the project every time we save.

 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)/})}}}Copy the code

3. In VScode, irregularities are highlighted when writing code and automatically formatted as normal code when Ctrl+S is saved. This is also a nice operation for me, I don’t have to change it in a single place.

Add eslint and vetur plugins to vscode:

After installing the plugin it is best to restart VScode and you will see the code in the project that does not conform to the specification you defined will be highlighted as shown below:

Finally, and best of all, configure Ctrl+S to automatically normalize the code when saving

  • Find the code => Preferences => Settings => settings.json file
  • Then modify the settings.json file
  • Here is my settings.json file for reference
{
    "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": "".// The size of TAB is 2 Spaces
    "editor.tabSize": 2."eslint.autoFixOnSave": true."eslint.options": {
        "extensions": [
            ".js".".vue"]},"eslint.validate": [
        "javascript",
        {
            "language": "vue"."autoFix": true
        },
        "html"."vue"].// // Format when saving
    "editor.formatOnSave": false.// // Enable vscode file path navigation
    "breadcrumbs.enabled": true.// Displays special characters generated when markDown is switched between Chinese and English
    "editor.renderControlCharacters": true.// eslint checks file types
    "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": {
            "File suffix": "Add something before the header comment of the file suffix."
        },
        "afterAnnotation": {
            "File suffix": "Add something to the file after a header comment with the suffix."
        },
        "specialOptions": {
            "Special Field": "Custom such as LastEditTime/LastEditors"
        },
        "switch": {
            "newlineAddAnnotation": true
        },
        "supportAutoLanguage": []."prohibitAutoAdd": [
            "json"]."folderBlacklist": [
            "node_modules"."Do not automatically add header comments to folders."]."prohibitItemAutoAdd": [
            "Full name of the project. Automatic header comments are not allowed for the entire project. You can use shortcut keys to add headers."]."moveCursor": true."dateFormat": "YYYY-MM-DD HH:mm:ss"."atSymbol": [
            "@"."@"]."atSymbolObj": {
            "File suffix": [
                "Header comment @ symbol"."Function comment @ symbol"]},"colon": [
            ":".":"]."colonObj": {
            "File suffix": [
                "Header comment colon"."Function comment colon"]},"filePathColon": "Path separator Replacement"."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
    },
    // File header comment
    "fileheader.customMade": {
        "Descripttion":""."version":"1.0.0"."Author":"[email protected]"."Date":"Do not edit".// No need to set, automatically generated after pressing the shortcut key
        "LastEditors":"[email protected]"."LastEditTime":"Do not Edit"// No need to set, automatically generated after pressing the shortcut key
    },
    // Function comments
    "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"],}Copy the code

Then go back to the above file, enter the file, just need Ctrl+S to save, the code automatically formatted, as shown in the picture:

Quick and easy! In a word: cool

advice

If you have strict code cleanliness for your code or if you have mandatory code writing practices for your team, the combination of the two will make your code easier and more elegant to manage.

Anything else that makes good use of the first point, I think, requires a good look at the documentation (API) so that you can understand it better.