天天看點

前端h5項目統一代碼風格配置(eslint + stylelint + prettier + lint-staged)一、概述二、editorConfig三、eslint四、stylelint五、prettier六、husky + lint-staged七、typeScript 校驗

2021-12-28 更新

husky

v7 版本的配置方式已經完全改變,官方位址,配置方式:

  • package.json

    的scripts裡添加指令:
  • npm run prepare

    運作指令,會自動在項目根目錄建立

    .husky

    檔案夾
  • 然後運作

    npx husky add .husky/pre-commit "npm run lint"

    ,會自動在

    .husky

    目錄添加

    pre-commit

    檔案,并添加了相應的git hooks檔案,

    pre-commit

    檔案裡也自動寫入了

    npm run lint

    内容,具體内容可自定義。
  • 上一步加了

    npm run lint

    的内容,意思就是git commit的時候自動執行npm run lint指令來校驗,是以需要在

    package.json

    的scripts裡添加指令,lint指令内容根據需要自行修改:
  • 大功告成。另外,關于團隊合作方面,其實在執行

    npm i

    的時候會自動執行

    npm run prepare

    指令,并根據.husky目錄的鈎子檔案自動生成相關的其他檔案,是以,隻要不删prepare指令,不忽略.husky檔案夾,團隊配置一緻性就沒有問題。

lint-staged

v12 版本的配置同樣也跟着

husky

變了,具體參考官方文檔。

一、概述

這裡的統一代碼風格包括編輯器基本配置、代碼校驗、格式化工具、git送出前校驗等,強烈建議配置下,特别是eslint起初可能不習慣,其實三五天時間就适應了,能幫助避免很多低級錯誤,另外對于團隊開發也很重要。

先介紹下這裡需要用到的幾個工具:

  • editorconfig

    統一編輯器基本配置
  • eslint

    js校驗工具。
  • stylelint

    css校驗工具,也支援less等css預處理器。
  • prettier

    代碼格式化工具,主要用于格式化html部分的代碼,一般寫代碼習慣好就不需要這個,可配置項很少,有點雞肋吧,但有總比沒有強,雖然我配置後從來沒用到過。。。
  • husky

    是一個gitHook工具,可以配置git的一些鈎子,本文主要用來配置 commit 鈎子。
  • lint-staged

    是一個在git暫存檔案上運作lint校驗的工具,配合husky配置commit鈎子,用于git commit前的強制校驗。

二、editorConfig

因為前端開發有些人用vscode,也有一部分人用webstorm,有些人用tab縮進,有些人用倆空格縮進,有些人用四個空格縮進,等等這些,這個工具就是用于統一不同人編輯器的項目配置。

  • 對于vscode,需要安裝擴充:

    EditorConfig for VS Code

  • 然後項目根目錄添加檔案

    .editorconfig

    ,編寫以下配置:
# https://editorconfig.org
root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = crlf
insert_final_newline = true
trim_trailing_whitespace = true

[*.md]
insert_final_newline = false
trim_trailing_whitespace = false
           

三、eslint

js校驗必備,注意eslint隻針對js或ts做校驗,按以下方式配置完後可做到儲存時自動校驗并修複,但是建議寫代碼時還是按照規範來寫,不要太依賴它的自動修複功能。

1、配置vscode

  • 安裝vscode擴充

    eslint

  • 設定檔案

    settings.json

    裡添加配置
"eslint.validate": [
  "html",
  "vue",
  "vue-html",
  "javascript",
  "javascriptreact", 
  "typescript",
  "typescriptreact"
],
"editor.codeActionsOnSave": {
  "source.fixAll.eslint": true,
  "source.fixAll.stylelint": true
},
           

2、對于通用js項目

推薦使用standard配置規範。

(1)項目安裝依賴

npm i -D eslint eslint-config-standard eslint-plugin-standard eslint-plugin-promise eslint-plugin-import eslint-plugin-node
           

(2)添加項目配置檔案

  • 項目根目錄添加eslint配置檔案

    .eslintrc.js

module.exports = {
  env: {
    commonjs: true,
    es6: true,
    node: true
  },
  extends: [
    'standard',
    'eslint:recommended',
  ],
  globals: {
  },
  parserOptions: {
    ecmaVersion: 11
  },
  rules: {
    'no-console': 'off',
    'no-debugger': 'off',
  }
}
           
  • 項目根目錄添加eslint忽略配置檔案

    .eslintignore

.DS_Store
node_modules
dist
build
public
.eslintrc.js
           

(3)可選

(非必需項,可能會影響webpack編譯速度,謹慎使用)

對于webpack項目,

eslint-webpack-plugin

可以幫助在webpack編譯或熱更新時實時校驗代碼并作出錯誤提示,替代以前的eslint-loader。

  • 安裝依賴:
npm i eslint-webpack-plugin -D
           
  • 在webpack的plugins配置檔案(例如

    webpack.base.conf.js

    )裡添加:
const ESLintPlugin = require('eslint-webpack-plugin');

module.exports = {
  // ...
  plugins: [
  	...
  	new ESLintPlugin({
		extensions: [
			'vue', 'html', 'js', 'ts', 'jsx', 'tsx'
		]
	})
  ],
  // ...
}
           

3、對于vue-cli腳手架項目

推薦使用官方腳手架預設的eslint校驗配置,如果在一開始用腳手架生成項目時未選擇eslint,可以通過以下方式手動添加:

(1)項目安裝依賴包

npm i -D @vue/cli-plugin-eslint @vue/eslint-config-standard babel-eslint eslint eslint-plugin-vue
           

(2)添加項目配置檔案

  • 項目根目錄添加eslint配置檔案

    .eslintrc.js

module.exports = {
  root: true,
  env: {
    node: true
  },
  extends: [
    'plugin:vue/essential',
    '@vue/standard'
  ],
  parserOptions: {
    parser: 'babel-eslint'
  },
  globals: {},
  rules: {
    'no-console': 'off',
    'no-debugger': 'off'
  },
}
           
  • 項目根目錄添加eslint忽略配置檔案

    .eslintignore

public
dist
           

4、對于create-react-app腳手架項目

推薦使用 eslint-config-standard + eslint-plugin-react

(1)項目安裝依賴包

npm i -D eslint eslint-config-standard eslint-plugin-standard eslint-plugin-promise eslint-plugin-import eslint-plugin-node eslint-plugin-react
           

(2)添加項目配置檔案

  • 項目根目錄添加eslint配置檔案

    .eslintrc.js

module.exports = {
  env: {
    browser: true,
    es2020: true,
    node: true
  },
  extends: [
    'standard',
    'eslint:recommended',
    'plugin:react/recommended'
  ],
  parser: 'babel-eslint',
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 11,
    sourceType: 'module'
  },
  plugins: [],
  settings: {
    react: {
      version: 'detect'
    }
  },
  rules: {
    'no-console': 'off',
    'no-debugger': 'off',
    'space-before-function-paren': 'off',
    'camelcase': 'off',
    'comma-dangle': 'off',
    'react/prop-types': 'off',
    'react/display-name': 'off'
  }
}
           
  • 項目根目錄添加eslint忽略配置檔案

    .eslintignore

scripts
config
public
build
.eslintrc.js
           

四、stylelint

stylelint隻針對css或css預處理器的代碼做校驗。(注意:配置了vscode後會對所有項目所有檔案的樣式代碼都生效,不管你項目裡有沒有相關配置檔案,謹慎使用)。

1、配置vscode

  • 安裝vscode擴充

    stylelint

  • 設定檔案

    settings.json

    裡添加配置
"editor.codeActionsOnSave": {
  "source.fixAll.eslint": true,
  "source.fixAll.stylelint": true
},
"css.validate": false,
"less.validate": false,
"scss.validate": false,
           
  • 如需要自定義編輯器預設配置,通過

    settings.json

    裡配置

    stylelint.configOverrides

    的rules實作:
// 這裡的配置優先級低于.stylelintrc.js檔案,适合用作編輯器的預設配置
"stylelint.configOverrides": {
  "rules": {
    // 示例,配置支援小程式rpx機關
    "unit-no-unknown": [true,
      { "ignoreUnits": ["rpx"] }
    ],
  },
  // 示例,配置忽略清單檔案
  "ignoreFiles": [
	  "node_modules/**/*",
	  "dist/**/*",
	  "**/*.js",
	  "**/*.jsx",
	  "**/*.tsx",
	  "**/*.ts"
	]
},
           

2、安裝依賴包

npm i stylelint stylelint-config-standard -D
           

3、添加項目配置檔案

  • 項目根目錄添加 .stylelintrc.js
module.exports = {
  extends: ['stylelint-config-standard'],
  rules: {
    'rule-empty-line-before': null,
    'font-family-no-missing-generic-family-keyword': null,
    'no-descending-specificity': null,
    'color-hex-case': null,
    'no-empty-source': null,
    'block-no-empty': null,
    "selector-pseudo-class-no-unknown": [true,
      { "ignorePseudoClasses": ["global"] }
    ]
  },
  ignoreFiles: [
    'node_modules/**/*',
    'public/**/*',
    'dist/**/*',
    '**/*.js',
    '**/*.jsx',
    '**/*.tsx',
    '**/*.ts'
  ],
}
           

ps:關于

stylelint-webpack-plugin

插件,功能類似于eslint的

eslint-webpack-plugin

,經實測會影響webpack熱更新速度,不建議使用。

五、prettier

prettier是一套代碼格式規範,一般用作格式化工具,但是配置項太少,和eslint的格式效果也可能會有沖突,是以不建議開啟編輯器的儲存自動格式化功能,js交給eslint,css交給stylelint,這個主要就用于html部分的格式化。

對個人編碼習慣不好的懶癌童鞋有奇效,對于習慣良好的還是按照自己的習慣就好,不過還是建議試用一下它的格式化效果和自己的代碼對比下,取長補短,形成自己的最佳實踐。

1、添加項目配置檔案

  • 項目根目錄添加

    .prettierrc.js

module.exports = {
  'eslintIntegration': true,
  'stylelintIntegration': true,
  'tabWidth': 2,
  'singleQuote': true,
  'semi': false
}
           

2、配置vscode

  • vscode添加擴充:

    Prettier

  • 設定檔案

    settings.json

    裡添加配置
"[html]": {
  "editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[css]": {
  "editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[less]": {
  "editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[scss]": {
  "editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascript]": {
  "editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[vue]": {
  "editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescript]": {
  "editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascriptreact]": {
  "editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescriptreact]": {
  "editor.defaultFormatter": "esbenp.prettier-vscode"
},

"prettier.singleQuote": true,
"prettier.semi": false,

"vetur.format.defaultFormatter.html": "prettier",
"vetur.format.defaultFormatterOptions": {
  "prettier": {
    "eslintIntegration": true,
	"stylelintIntegration": true
  }
},
           

六、husky + lint-staged

隻是單純引入校驗如果不強制要求就等于沒做,總會有人偷懶,是以還是要限制一下。

  • husky

    用于git執行鈎子前做校驗,
  • lint-staged

    用于隻校驗git暫存區的檔案。
  • 這裡要實作的功能是在

    git commit

    指令運作時先校驗lint(包括eslint和stylelint)是否通過,未通過則不予commit。

1、安裝依賴包

npm i [email protected] [email protected] -D
           

2、配置package.json

  • scripts裡添加指令eslint 和 stylelint:
"scripts": {
   "eslint": "eslint--config .eslintrc.js **/*.{vue,html,js,ts,jsx,tsx} --fix",
   "stylelint": "stylelint --config .stylelintrc.js **/*.{vue,html,css,less,scss,sass} --fix"
 }
           
  • 添加 lint-staged 相關配置:
"husky": {
   "hooks": {
     "pre-commit": "lint-staged"
   }
},
"lint-staged": {
   "*.{vue,html,js,ts,jsx,tsx}": [
     "npm run eslint"
   ],
   "*.{vue,html,css,less,scss,sass}": [
     "npm run stylelint"
   ]
},
           

這裡的配置對vue和react以及ts檔案拓展名都做了通用的判斷處理,實際項目中可以移除用不到的拓展名;

需要注意,強制校驗相關的控制檔案都是在.git檔案夾内,如果不小心删除了這個檔案夾,需要重新安裝依賴包(husky)後強制校驗才能生效。

七、typeScript 校驗

如果項目使用ts代碼,需要額外配置ts相關的校驗。

1、配置指引

首先需要按上述的eslint配置教程配置好eslint,然後再往下看。

(1)vue-cli項目

仍然是推薦使用官方腳手架預設的ts校驗配置,如果在用腳手架生成項目時未選擇ts,可按以下方式配置:

  • 安裝依賴:
npm i D typescript @vue/cli-plugin-typescript @vue/eslint-config-typescript @typescript-eslint/[email protected] @typescript-eslint/[email protected] 
           
  • 修改

    .eslintrc.js

module.exports = {
  root: true,
  env: {
    node: true
  },
  extends: [
    'plugin:vue/essential',
    '@vue/standard',
    '@vue/typescript/recommended' // 修改點一
  ],
  parserOptions: {
    ecmaVersion: 2020 // 修改點二
  },
  globals: {},
  rules: {
    'no-console': 'off',
    'no-debugger': 'off'
  }
}
           

(2)create-react-app項目

  • 插件

    typescript-eslint

    用作ts校驗,是eslint的一個擴充插件,引入後修改

    .eslintrc.js

    配置即可,具體使用配置參考插件官方教程,步驟已經非常詳細,這裡就不多說了,也可以參考文末的附錄作對比;
  • 插件tslint已經停止維護,不建議使用;
  • 如果遇到類似的ts校驗報錯資訊:‘React’ was used before it was defined

    需要在

    .eslintrc.js

    裡添加以下rules規則:
"no-use-before-define": "off",
"@typescript-eslint/no-use-before-define": ["error"],
           

2、其他注意點

  • lint-staged相關配置裡需要添加.ts字尾檔案的支援,如果是react項目還要添加.jsx和.tsx檔案支援。
  • vscode下有時會有莫名其妙ts不生效的問題,嘗試解決方法:把項目檔案夾拖到vscode以工作區的形式顯示,并将該項目拖到最頂部使其在工作區排在第一位,然後重新開機vscode。

3、附錄

(1)eslintrc.js

附上react+ts項目的

.eslintrc.js

配置供參考:

module.exports = {
  env: {
    browser: true,
    es2020: true,
    node: true
  },
  extends: [
    'standard',
    'eslint:recommended',
    'plugin:react/recommended',
    'plugin:@typescript-eslint/recommended'
  ],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 11,
    sourceType: 'module'
  },
  plugins: [],
  settings: {
    react: {
      version: 'detect'
    }
  },
  rules: {
    'no-console': 'off',
    'no-debugger': 'off',
    'space-before-function-paren': 'off',
    'camelcase': 'off',
    'comma-dangle': 'off',
    'react/prop-types': 'off',
    'react/display-name': 'off',
    '@typescript-eslint/member-delimiter-style': 0,
    '@typescript-eslint/no-explicit-any': 0,
    '@typescript-eslint/triple-slash-reference': 0,
    '@typescript-eslint/explicit-module-boundary-types': 0,
    "no-use-before-define": "off",
	"@typescript-eslint/no-use-before-define": ["error"],
  }
}
           

(2)相關依賴版本:

"@typescript-eslint/eslint-plugin": "^4.0.1",
"@typescript-eslint/parser": "^4.0.1",
"eslint": "^7.9.0",
"eslint-config-standard": "^14.1.1",
"eslint-loader": "^4.0.2",
"eslint-plugin-import": "^2.22.0",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-react": "^7.21.1",
"eslint-plugin-standard": "^4.0.1",
           

繼續閱讀