天天看點

配置 ESLint 自動格式化自閉合标簽(Self closing tag)

對于沒有子元素或不需要子元素的 HTML 标簽,通常寫成其自閉合的形式會顯得簡潔些,
- <SomeComponent></SomeComponent>
+ <SomeComponent/>      
通過配置 ESLint 可在格式化的時候将标簽自動變成自閉合形式。

create-react-app

如果是使用

create-react-app

建立的項目,直接在 package.json 的 eslint 配置部分加上如下配置即可:
"eslintConfig": {
    "extends": "react-app",
+   "rules": {
+     "react/self-closing-comp": [
+       "error"
+     ]
    }      

安裝依賴

安裝 ESLint 相關依賴:
$ yarn add eslint eslint-plugin-react      
如果是 TypeScript 項目,還需要安裝如下插件:
$ yarn add @typescript-eslint/eslint-plugin  @typescript-eslint/parser      

配置 ESLint

通過

yarn eslint --init

向導來完成建立,

或手動建立

.eslintrc.json

填入如下配置:
{
  "extends": ["eslint:recommended", "plugin:react/recommended"],
  "parser": "@typescript-eslint/parser",
  "plugins": ["react", "@typescript-eslint"],
  "rules": {
    "react/self-closing-comp": ["error"]
  }
}      

安裝 ESLint for Vscode

當然了,還需要安裝 VSCode 插件 dbaeumer.vscode-eslint。

然後配置 VSCode 在儲存時自動進行修正動作:

"editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },      

使用

完成上述配置後,如果發現儲存時,格式并未生效,或者隻 JavaScript 檔案生效,需要補上如下的 VSCode 配置:
"eslint.validate": [
    "javascript",
    "javascriptreact",
    "typescript",
    "typescriptreact",
  ]
           
也可檢視 VSCode 的狀态欄,看是否有報錯可确定是什麼原因導緻 ESLint 工作不正常,比如 mac BigSur 中細化了權限,需要點選警告圖示然後點選允許。
配置 ESLint 自動格式化自閉合标簽(Self closing tag)

相關資源

  • eslint-plugin-react
  • ESLint in VSC not working for .ts and .tsx files
The text was updated successfully, but these errors were encountered:
配置 ESLint 自動格式化自閉合标簽(Self closing tag)

CC BY-NC-SA 署名-非商業性使用-相同方式共享