Visual studio code changes format (React-JSX)

2019-01-22 13:40发布

问题:

I've the following snippet in my index.js

class App extends Component {
render() {
    return ( <div style = { styles.app } >
        Welcome to React!
        </div>
    )
}

}
The code works, but every time I save (ctrl+s) visual studio format the jsx like that:

class App extends Component {
render() {
    return ( < div style = { styles.app } >
        Welcome to React!
        <
        /div>
    )
}

}

How can I solve this? thanks

回答1:

Alternatively, saving the file with a .jsx extension resolves this in vscode.

I had the same challenge and I am hoping to discover a better way of handling this issue in vscode.

I noticed your suggested work-around has to be done each time you open the react file with an extension of .js



回答2:

In the end what did the trick was changing the file format from JavaScript to JavaScript React on the bottom toolbar. I'm publishing it here for future reference since I didn't find any documentation on this topic.

In addition to the above. If you click 'Configure File Association for .js' you can set all .js files to Javascript React



回答3:

change vscode preferences settings > user settings below:

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


回答4:

Install Prettier (if not installed by default) and try to add this to 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.



回答5:

You can install an extension like react-beautify that helps you format your jsx code.

It is found here

This extension wraps prettydiff/esformatter to format your javascript, JSX, typescript, TSX file.



回答6:

Make sure you dont have multiple javascript formatters enabled in your current workspace. (You have to disable the rest of them for your current workspace).

react-beautify mostly does the magic but fails if you have some other JS formatter/beautifier already installed.

In my case, I had react-beautify and JS-CSS-HTML Formatter extension installed. I had to disable the JS-CSS-HTML Formatter for my current workspace.



回答7:

I had similar problem, then I found out it was caused by 'beautify' extension. After I uninstalled the extension, everything is working fine.