溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何實現(xiàn)vue3+ts+EsLint+Prettier規(guī)范代碼

發(fā)布時間:2021-10-25 16:21:58 來源:億速云 閱讀:178 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容主要講解“如何實現(xiàn)vue3+ts+EsLint+Prettier規(guī)范代碼”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“如何實現(xiàn)vue3+ts+EsLint+Prettier規(guī)范代碼”吧!

使用

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,從而檢查和規(guī)范Typescript代碼

  • - `@typescript-eslint/eslint-plugin`:這是一個ESLint插件,包含了各類定義好的檢測Typescript代碼的規(guī)范

添加配置文件

npx eslint --init

根目錄下增加.eslintrc.js文件。(建議選擇js文件,json不可以寫注釋) 修改配置文件
主要是修改rules中的相關(guān)配置,具體可查看官方配置

/*!
 * 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中的樣式規(guī)范和prettier中樣式規(guī)范的沖突,以prettier的樣式規(guī)范為準,使ESLint中的樣式規(guī)范自動失效

  • - `eslint-plugin-prettier`:將prettier作為ESLint規(guī)范來使用

添加配置文件

在項目的根目錄下創(chuàng)建`.prettierrc.js`文件,并添加如下配置

module.exports = {
  printWidth: 120, // 換行字符串閾值
  tabWidth: 2, // 設(shè)置工具每一個水平縮進的空格數(shù)
  useTabs: false,
  semi: false, // 句末是否加分號
  vueIndentScriptAndStyle: true,
  singleQuote: true, // 用單引號
  trailingComma: 'none', // 最后一個對象元素加逗號
  bracketSpacing: true, // 對象,數(shù)組加空格
  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中的樣式規(guī)范失效,遵循prettier中的樣式規(guī)范

  • - `plugin:prettier/recommended`:使用prettier中的樣式規(guī)范,且如果使得ESLint會檢測prettier的格式問題,同樣將格式問題以error的形式拋出

使用husky和lint-staged構(gòu)建代碼

安裝依賴

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

這樣,在執(zhí)行g(shù)it 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"
  ]
}

到此,相信大家對“如何實現(xiàn)vue3+ts+EsLint+Prettier規(guī)范代碼”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學習!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI