vue3+ts+EsLint+Prettier standard code implementation

vue3+ts+EsLint+Prettier standard code implementation

This article mainly introduces how to install and configure EsLint and Prettier when using TypeScript for development in Vue3 to improve coding standards.
(1) EsLint provides coding standards;
(2) Prettier is an Opinionated code formatting tool.

use

Use of EsLint

Install Dependencies

npm i -D eslint eslint-plugin-vue @typescript-eslint/parser @typescript-eslint/eslint-plugin

The four dependencies are:

  • - `eslint`: EsLint's core code
  • - `eslint-plugin-vue`: [A plugin for using Eslint for Vue](https://eslint.vuejs.org/)
  • - `@typescript-eslint/parser`: ESLint's parser, used to parse typescript, thereby checking and standardizing Typescript code
  • - `@typescript-eslint/eslint-plugin`: This is an ESLint plugin that contains various defined specifications for detecting Typescript code

Add a profile

npx eslint --init

Add .eslintrc.js file in the root directory. (It is recommended to select js file, json cannot write comments) Modifying the configuration file mainly modifies the relevant configuration in rules. For details, please refer to the official configuration

/*!
 * https://eslint.bootcss.com/docs/rules/
 * https://eslint.vuejs.org/rules/
 *
 * - 0: off
 * - 1: warn
 * - 2: error
 */
module.exports = {
  root: true,
  env: {
    browser: true,
    node: true,
    es6: true
  },
  parser: 'vue-eslint-parser',
  parserOptions: {
    parser: '@typescript-eslint/parser',
    ecmaVersion: 2020,
    sourceType: 'module',
    jsxPragma: 'React',
    ecmaFeatures: {
      jsx: true
    }
  },
  globals:
    AMap: false,
    AMapUI: false
  },
  extends: [
    'plugin:vue/vue3-recommended',
    'plugin:@typescript-eslint/recommended',
    'prettier',
    'plugin:prettier/recommended'
  ],
  rules:
    '@typescript-eslint/ban-ts-ignore': 'off',
    '@typescript-eslint/explicit-function-return-type': 'off',
    '@typescript-eslint/no-explicit-any': 'off',
    '@typescript-eslint/no-var-requires': 'off',
    '@typescript-eslint/no-empty-function': 'off',
    'vue/custom-event-name-casing': 'off',
    'no-use-before-define': 'off',
    '@typescript-eslint/no-use-before-define': 'off',
    '@typescript-eslint/ban-ts-comment': 'off',
    '@typescript-eslint/ban-types': 'off',
    '@typescript-eslint/no-non-null-assertion': 'off',
    '@typescript-eslint/explicit-module-boundary-types': 'off',
    '@typescript-eslint/no-unused-vars': [
      'error',
      {
        argsIgnorePattern: '^_',
        varsIgnorePattern: '^_'
      }
    ],
    'no-unused-vars': [
      'error',
      {
        argsIgnorePattern: '^_',
        varsIgnorePattern: '^_'
      }
    ],
    'space-before-function-paren': 'off',
    'vue/name-property-casing': ['error', 'PascalCase'], // vue/component-definition-name-casing enforces a specific size for component definition names 'vue/attributes-order': 'off',
    'vue/one-component-per-file': 'off',
    'vue/html-closing-bracket-newline': 'off',
    'vue/max-attributes-per-line': 'off',
    'vue/multiline-html-element-content-newline': 'off',
    'vue/singleline-html-element-content-newline': 'off',
    'vue/attribute-hyphenation': 'off',
    'vue/require-default-prop': 'off',
    'vue/script-setup-uses-vars': 'off',
    'vue/html-self-closing': [
      'error',
      {
        html: {
          void: 'always',
          normal: 'never',
          component: 'always'
        },
        svg: 'always',
        math: 'always'
      }
    ]
  }
}

Use of Prettier

Install Dependencies

npm i --save-dev prettier eslint-config-prettier eslint-plugin-prettier

The three dependencies are:

  • - `prettier`: the core code of the prettier plugin
  • - `eslint-config-prettier`: resolves the conflict between the style specifications in ESLint and prettier, and takes prettier's style specifications as the priority, automatically invalidating the style specifications in ESLint
  • - `eslint-plugin-prettier`: Use prettier as ESLint specification

Add a profile

Create a .prettierrc.js file in the root directory of the project and add the following configuration

module.exports = {
  printWidth: 120, // Line break string threshold tabWidth: 2, // Set the number of spaces for each horizontal indentation of the tool useTabs: false,
  semi: false, // Whether to add a semicolon at the end of the sentence vueIndentScriptAndStyle: true,
  singleQuote: true, // Use single quotes trailingComma: 'none', // Add a comma to the last element of an object bracketSpacing: true, // Add spaces to objects and arrays jsxBracketSameLine: true, // Does jsx > start a new line arrowParens: 'always', // Does (x) => {} need parentheses requirePragma: false, // No need to write @prettier at the beginning of the file
  insertPragma: false // No need to automatically insert @prettier at the beginning of the file
}

Adding Prettier to EsLint

Modify the `.eslintrc.js` file and add in extends

    'prettier',
    'plugin:prettier/recommended'

in:

  • - `prettier/@typescript-eslint`: invalidates the style specification in @typescript-eslint and follows the style specification in prettier
  • - `plugin:prettier/recommended`: Use the style specifications in prettier, and if ESLint is enabled, it will detect formatting issues in prettier and also throw formatting issues as errors

Build code using husky and lint-staged

Install Dependencies

npm i --save-dev husky lint-staged

Modify package.json
Add the following code

    "husky": {
        "hooks": {
            "pre-commit": "lint-staged"
        }
    },
    "lint-staged": {
        "src*/**/*.ts": [
            "prettier --config .prettierrc.js --write",
            "eslint",
            "git add"
        ],
        "src*/**/*.json": [
            "prettier --config .prettierrc.js --write",
            "eslint",
            "git add"
        ]
    }

In this way, when you execute git commit, EsLint will check the submitted code.

Add setting.json configuration

Add the `setting.json` configuration file in the .vscode folder to automatically repair and verify the code when automatically saving.

{
  "typescript.tsdk": "./node_modules/typescript/lib",
  "typescript.enablePromptUseWorkspaceTsdk": true,
  "volar.tsPlugin": true,
  "volar.tsPluginStatus": false,
  //===========================================
  //============= Editor ======================
  //===========================================
  "explorer.openEditors.visible": 0,
  "editor.tabSize": 2,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "diffEditor.ignoreTrimWhitespace": false,
  //===========================================
  //============= Other =======================
  //===========================================
  "breadcrumbs.enabled": true,
  "open-in-browser.default": "chrome",
  //===========================================
  //============= files =======================
  //===========================================
  "files.eol": "\n",
  "search.exclude": {
    "**/node_modules": true,
    "**/*.log": true,
    "**/*.log*": true,
    "**/bower_components": true,
    "**/dist": true,
    "**/elehukouben": true,
    "**/.git": true,
    "**/.gitignore": true,
    "**/.svn": true,
    "**/.DS_Store": true,
    "**/.idea": true,
    "**/.vscode": false,
    "**/yarn.lock": true,
    "**/tmp": true,
    "out": true,
    "dist": true,
    "node_modules": true,
    "CHANGELOG.md": true,
    "examples": true,
    "res": true,
    "screenshots": true,
    "yarn-error.log": true,
    "**/.yarn": true
  },
  "files.exclude": {
    "**/.cache": true,
    "**/.editorconfig": true,
    "**/.eslintcache": true,
    "**/bower_components": true,
    "**/.idea": true,
    "**/tmp": true,
    "**/.git": true,
    "**/.svn": true,
    "**/.hg": true,
    "**/CVS": true,
    "**/.DS_Store": true
  },
  "files.watcherExclude": {
    "**/.git/objects/**": true,
    "**/.git/subtree-cache/**": true,
    "**/.vscode/**": true,
    "**/node_modules/**": true,
    "**/tmp/**": true,
    "**/bower_components/**": true,
    "**/dist/**": true,
    "**/yarn.lock": true
  },
  "stylelint.enable": true,
  "stylelint.packageManager": "yarn",
  "liveServer.settings.donotShowInfoMsg": true,
  "telemetry.enableCrashReporter": false,
  "workbench.settings.enableNaturalLanguageSearch": false,
  "path-intellisense.mappings": {
    "/@/": "${workspaceRoot}/src"
  },
  "prettier.requireConfig": true,
  "typescript.updateImportsOnFileMove.enabled": "always",
  "workbench.sideBar.location": "left",
  "[javascriptreact]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[typescript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[typescriptreact]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[html]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[css]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[less]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[scss]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[markdown]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "[vue]": {
    "editor.codeActionsOnSave": {
      "source.fixAll.eslint": false
    }
  },
  "cSpell.words": [
    "vben",
    "windi",
    "browserslist",
    "tailwindcss",
    "esnext",
    "antv",
    "tinymce",
    "qrcode",
    "sider",
    "pinia",
    "sider",
    "nprogress"
  ]
}

References

Prettier official website
EsLint official website
EsLint Rules
Prettier Just read this article Use EsLint+Prettier to standardize TypeScript code

This is the end of this article about the implementation of vue3+ts+EsLint+Prettier standard code. For more relevant vue3 ts standard code content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of the use of ESLint in Vue
  • Vue scaffolding vue-cli learning and use tutorial
  • How to use eslint and editorconfig in Vue

<<:  How to change the website accessed by http to https in nginx

>>:  W3C Tutorial (7): W3C XSL Activities

Recommend

Vue+js click arrow to switch pictures

This article example shares the specific code of ...

Introduction to Enterprise Production MySQL Optimization

Compared with other large databases such as Oracl...

uniapp dynamic modification of element node style detailed explanation

Table of contents 1. Modify by binding the style ...

Configure Mysql master-slave service implementation example

Configure Mysql master-slave service implementati...

A brief discussion on creating cluster in nodejs

Table of contents cluster Cluster Details Events ...

Use of Linux ifconfig command

1. Command Introduction The ifconfig (configure a...

Detailed explanation of Tomcat core components and application architecture

Table of contents What is a web container? The Na...

Detailed example of MySQL data storage process parameters

There are three types of MySQL stored procedure p...

Complete steps to implement face recognition login in Ubuntu

1. Install Howdy: howdy project address sudo add-...

Vue3.0+vite2 implements dynamic asynchronous component lazy loading

Table of contents Create a Vite project Creating ...

Detailed explanation of the execution principle of MySQL kill command

Table of contents Kill instruction execution prin...

Detailed explanation of meta tags (the role of meta tags)

No matter how wonderful your personal website is,...

How to use Dockerfile to build images in Docker

Build the image Earlier we used various images fo...

Detailed explanation on reasonable settings of MySQL sql_mode

Reasonable setting of MySQL sql_mode sql_mode is ...