vue3+ts+EsLint+Prettier规范代码的方法实现

2022-04-15 0 459
目录
  • 使用
    • EsLint的使用
    • 添加配置文件
    • Prettier的使用
  • 使用husky和lint-staged构建代码
    •  增加setting.json配置
      • 参考资料

        本文主要介绍在Vue3中使用TypeScript做开发时,如何安装与配置EsLint和Prettier,以提高编码规范。
        (1)EsLint 提供编码规范;
        (2)Prettier 是一个 Opinionated 的代码格式化工具。

        使用

        EsLint的使用

        安装依赖

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

        这四个依赖分别是:

        • – `eslint`: EsLint的核心代码
        • – `eslint-plugin-vue`:[为Vue使用Eslint的插件](https://eslint.vuejs.org/)
        • – `@typescript-eslint/parser`:ESLint的解析器,用于解析typescript,从而检查和规范Typescript代码
        • – `@typescript-eslint/eslint-plugin`:这是一个ESLint插件,包含了各类定义好的检测Typescript代码的规范

        添加配置文件

        npx eslint --init
        

        根目录下增加.eslintrc.js文件。(建议选择js文件,json不可以写注释) 修改配置文件
        主要是修改rules中的相关配置,具体可查看官方配置

        /*!
         * 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 对组件定义名称强制使用特定的大小
            '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'
              }
            ]
          }
        }
        

        Prettier的使用

        安装依赖

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

        这三个依赖分别是:

        • – `prettier`:prettier插件的核心代码
        • – `eslint-config-prettier`:解决ESLint中的样式规范和prettier中样式规范的冲突,以prettier的样式规范为准,使ESLint中的样式规范自动失效
        • – `eslint-plugin-prettier`:将prettier作为ESLint规范来使用

        添加配置文件

        在项目的根目录下创建`.prettierrc.js`文件,并添加如下配置

        module.exports = {
          printWidth: 120, // 换行字符串阈值
          tabWidth: 2, // 设置工具每一个水平缩进的空格数
          useTabs: false,
          semi: false, // 句末是否加分号
          vueIndentScriptAndStyle: true,
          singleQuote: true, // 用单引号
          trailingComma: 'none', // 最后一个对象元素加逗号
          bracketSpacing: true, // 对象,数组加空格
          jsxBracketSameLine: true, // jsx > 是否另起一行
          arrowParens: 'always', // (x) => {} 是否要有小括号
          requirePragma: false, // 不需要写文件开头的 @prettier
          insertPragma: false // 不需要自动在文件开头插入 @prettier
        }
        

        将Prettier添加到EsLint中

        修改`.eslintrc.js`文件,在extends中增加

            'prettier',
            'plugin:prettier/recommended'

        其中:

        • – `prettier/@typescript-eslint`:使得@typescript-eslint中的样式规范失效,遵循prettier中的样式规范
        • – `plugin:prettier/recommended`:使用prettier中的样式规范,且如果使得ESLint会检测prettier的格式问题,同样将格式问题以error的形式抛出

        使用husky和lint-staged构建代码

        安装依赖

        npm i --save-dev husky lint-staged
        

        修改package.json
        添加以下代码

            "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"
                ]
            }
        
        

        这样,在执行git commit时,EsLint会检查提交的代码。

         增加setting.json配置

        在.vscode文件夹中增加`setting.json`配置文件,用于自动保存时,自动修复及检验代码。

        {
          "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"
          ]
        }

        参考资料

        Prettier官网
        EsLint官网
        EsLint Rules
        Prettier看这一篇就行了
        使用EsLint+Prettier规范TypeScript代码

        到此这篇关于vue3+ts+EsLint+Prettier规范代码的方法实现的文章就介绍到这了,更多相关vue3 ts 规范代码内容请搜索NICE源码以前的文章或继续浏览下面的相关文章希望大家以后多多支持NICE源码!

        免责声明:
        1、本网站所有发布的源码、软件和资料均为收集各大资源网站整理而来;仅限用于学习和研究目的,您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。 不得使用于非法商业用途,不得违反国家法律。否则后果自负!

        2、本站信息来自网络,版权争议与本站无关。一切关于该资源商业行为与www.niceym.com无关。
        如果您喜欢该程序,请支持正版源码、软件,购买注册,得到更好的正版服务。
        如有侵犯你版权的,请邮件与我们联系处理(邮箱:skknet@qq.com),本站将立即改正。

        NICE源码网 JavaScript vue3+ts+EsLint+Prettier规范代码的方法实现 https://www.niceym.com/18430.html