Why does jsx code formatting not correctly

后端 未结 6 1322
说谎
说谎 2020-12-14 16:31

vscode is my favorite editor, I have a code formatting problem with it. Here is my jsx code:



        
相关标签:
6条回答
  • 2020-12-14 16:50

    Alternatively to Beautify and the workaround that you should do, you can use instead rc-beautify vscode extension. Install it, CTRL+B to format JS, JSX code.

    0 讨论(0)
  • 2020-12-14 16:59

    You did not wrote your file name, if it is an ".js" file, rename to ".jsx"

    0 讨论(0)
  • 2020-12-14 17:00

    Install Prettier (if not installed), and try to add this your user or workplace settings:

    "prettier.jsxBracketSameLine": true
    

    Do not put linebreak between return and the returned JSX expression. Trigger autoformat (Alt+Shift+F), and check if works.

    0 讨论(0)
  • 2020-12-14 17:05

    This is because vs code is recognising the language of .js files as "JavaScript" not "JavaScript React" and beautify uses the language that vs code says it is to decide how to format it.

    As suggested by other answers, you could manually select the language (in the bottom right corner of vs code) as "JavaScript React" or rename each file extension to .jsx but what I think is easier is to add:

    "files.associations": {
        "*.js": "javascriptreact",
    }
    

    into my workspace settings.json file.

    Now vs code will automatically recognise all .js files language as "JavaScript React" in the workspace!

    If your unsure how to get to this file, check this out User and Workspace Settings.

    Edit: This is useful if all the .js files in your workspace are "JavaScript React"!

    0 讨论(0)
  • 2020-12-14 17:07

    Choose the language in right-bottom corner as "JavaScript React".

    And a better way is to rename the js files to jsx.

    0 讨论(0)
  • 2020-12-14 17:08

    As you note, the Beautify extension is the root cause here (see this issue). That extension provides a document formatter that VSCode will run when you run the format command

    A few options:

    • Disable the extension
    • Disable Beautify for just js files by removing the js entry from the "beautify.language" setting
    • Make sure your file has a language mode of javascriptreact. I believe this will prevent Beautify from running on the file
    0 讨论(0)
提交回复
热议问题