简体   繁体   中英

How to setup self-closing when I save code on VSCode with prettier and ESLint?

I use React and VSCode, I wanna setup self-closing when code is saved but I don't know how...

What I wanna do is

<Hello></Hello>

after I save code

<Hello />

Where can I setup self closing?

Thank you.

You need to enable the related rule and make sure VSCode is integrated to fix lint warnings/errors on saving.

  1. Enable react/self-closing-comp rule:
// eslint config file (package.json / eslintrc / settings.json etc.)
{
  ...
  "rules": {
    "react/self-closing-comp": "error"
  }
}
  1. Within settings.json at VSCode make sure you got auto-fix enabled (for example with vscode-eslint extension, it may be any other lint extension related):
// settings.json @ VSCode
{ 
...
  "eslint.autoFixOnSave": true,
  "eslint.run": "onSave",
}

Refer to eslint-plugin for vscode for integration.

Note that eslint-config-airbnb enables it by default (I suggest using any config).

For as far as I know you can achieve something like that with "javascript.autoClosingTags": false . However I know that some part of the community really dislikes this feature since it often closes components that you don't want to be closed. I don't know if you are familiar with Typescript? But if you are I recommend using React in combination with type script (create a project by npx create-react-app . --typescript . While developing it automatically checks for these cases and gives you a compile error if you have an empty component.

I hope this answers your question

Add this ti vscode config:

vscode settings.json:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM