ESLint + Prettier + husky + lint-staged 規范統一前端代碼風格


寫在前面:

  • ESLint: Find and fix problems in your JavaScript code.
  • Prettier: Prettier is an opinionated code formatter. 
  • Husky: Husky can prevent bad git commit, git push and more.
  • Lint-staged: Run linters against staged git files and don't let 💩 slip into your code base!
  • EditorConfig: EditorConfig helps maintain consistent coding styles for multiple developers working on the same project across various editors and IDEs.
  • Stylelint: A mighty, modern linter that helps you avoid errors and enforce conventions in your styles.
  • 開發工具:VS Code、插件: Prettier,ESLint
  • 開發框架:React V16+、React CLI
  • 版本控制:Git
  • 參考資料:

搭建項目:

npx create-react-app [your-project-name]
cd [your-project-name]
npm run eject

 

 初始化 ESLint 配置文件:

./node_modules/.bin/eslint --init

根據問題選擇自己喜歡的配置(選錯也沒事,后面可以在配置文件里修改)完成以后會在項目根目錄生成 .eslintrc.js 文件。

.eslintrc.js:

module.exports = {
  env: {
    browser: true,
    es6: true,
    node: true,
  },
  extends: 'eslint:recommended',
  globals: {
    Atomics: 'readonly',
    SharedArrayBuffer: 'readonly',
    _: true,
  },
  parser: 'babel-eslint', // 解決 實驗性的 public class fields 語法 報錯問題
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 2018,
    sourceType: 'module',
  },
  plugins: ['react', 'react-hooks'],
  rules: {
    'react-hooks/rules-of-hooks': 'error', // 檢查 Hook 的規則
    'react-hooks/exhaustive-deps': 'warn', // 檢查 effect 的依賴
    indent: [
      'error',
      2,
      {
        SwitchCase: 1,
      },
    ],
    // 'linebreak-style': ['error', 'unix'], // 換行符 Mac:'unix' -> LF,win:'windows' -> CRLF
    quotes: ['error', 'single'],
    semi: ['error', 'always'],
    'multiline-ternary': ['error', 'always-multiline'], // 三目運算符換行
    'react/jsx-uses-react': 'error', // Prevent React to be incorrectly marked as unused
    'react/jsx-uses-vars': 'error', // Prevent variables used in JSX to be incorrectly marked as unused
    'no-console': 'off',
  },
};

 

初始化 Prettier 配置:

在根目錄下新建 .prettierrc.js 文件:

module.exports = {
  trailingComma: 'all',
  printWidth: 80,
  tabWidth: 2,
  semi: true,
  singleQuote: true,
  jsxBracketSameLine: true,
  jsxSingleQuote: true,
  arrowParens: 'always',
};

 

安裝 Prettier、husky、lint-staged: 

npm install --save-dev --save-exact prettier
npm install --save-dev husky
npm install --save-dev lint-staged

注意一定要使用 --save-dev 安裝在 devDependencies 下。

 

初始化 lint-staged 配置:

npx mrm lint-staged

完成后會在 package.json 中生成husky和lint-staged配置(以下為手動修改后的配置):

  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*.{js,jsx,css,less,json,md}": [
      "prettier --write",
      "git add"
    ],
    "**/*.less": "stylelint --syntax less",
    "**/*.{js,jsx}": "npm run lint-staged:js"
  },

 

配置 stylelint:

npm install stylelint --save-dev

在根目錄下新建 .stylelintrc.js 文件:

module.exports = {
  extends: 'stylelint-config-standard',
  rules: {
    'block-no-empty': true,
    'comment-empty-line-before': [
      'always',
      {
        ignore: ['stylelint-commands', 'after-comment'],
      },
    ],
    indentation: [2],
    'max-empty-lines': 2,
  },
};

 可能會遇到以下報錯:

Could not find "stylelint-config-standard". Do you need a `configBasedir`?

解決方案:

查看:stylelint-config-standard

npm install stylelint-config-standard --save-dev

 

配置package.json中的腳本命令:

"scripts": {
    "lint": "npm run lint:js && npm run lint:style && npm run lint:prettier",
    "lint-staged": "lint-staged",
    "lint-staged:js": "eslint --ext .js,.jsx,.ts,.tsx ",
    "lint:fix": "eslint --fix --cache --ext .js,.jsx,.ts,.tsx --format=pretty ./src && npm run lint:style",
    "lint:js": "eslint --cache --ext .js,.jsx,.ts,.tsx --format=pretty ./src",
    "lint:prettier": "check-prettier lint",
    "lint:style": "stylelint --fix \"src/**/*.less\" --syntax less",
    "prettier": "prettier -c --write \"**/*\""
  },

 

VS Code安裝 Prettier、ESLint 插件(不會的自行Google)

配置 VS Code 編輯器:

 

這里只示例配合 prettier 插件使用的配置,當保存文件的時候將自動格式化代碼:

{
    "editor.defaultFormatter": "esbenp.prettier-vscode",
    "editor.formatOnSave": true,
}

 

創建可移植的自定義編輯器設置:

在根目錄下新建 .editorconfig 文件,配置如下:

# http://editorconfig.org
root = true

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

[*.md]
trim_trailing_whitespace = false

[Makefile]
indent_style = tab

 

其他配置: 

如果不需要 ‘行結束符’配置,則 把 .editorconfig中的 end_of_line 和 .eslintrc.js 文件中 rules 下的 linebreak-style 注釋掉。

在項目根目錄新建 .gitattributes 文件,配置如下:

* text=auto

 

'linebreak-style': ['error', 'unix'], // 換行符。 Mac使用 'unix' 對應 LF,Win使用 'windows' 對應 CRLF

 

如果需要 ‘行結束符’ 配置,例如使用 LF 。則 .editorconfig 中配置 end_of_line = lf ,.eslintrc.js 中 rules 配置 linebreak-style: ['error', 'unix']

另外再給 VS Code 配置 "files.eol": "\n",最好再給 .gitattributes 添加配置 *.js text eol=lf  *.jsx text eol=lf 等等,全部提交之后,把本地項目文件全刪除,重新clone。

.gitattributes 配置參考網上的。一般不用這個 行結束符 配置。

參考:line endings

 

寫在最后:

以上配置均可在 寫在最前 的鏈接中找到,可以根據自己的風格進行配置。 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM