why vscode is not recognizing react code as react javascript instead it format it as vanilla javascript

10,269

Solution 1

I am using create-react-app so it produce the main component App.js I am using .JSX in the other components but the problem is when I make any change to the App.js

I fixed this issue by changing the files associations setting in Vscode settings (specific to user workspace)

I just added this line

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

and worked perfectly for me.

Solution 2

rename your react files as 'jsx' files instead of js files and keep your vanilla javascript as js files. This way vs code and prettier know that you are using react-javascript instead of normal javascript.

Solution 3

I don't read anything about react in prettier documentation

As far as I understand, react code should be put in .jsx files, not .js

https://reactjs.org/docs/introducing-jsx.html

React doesn’t require using JSX, but most people find it helpful as a visual aid when working with UI inside the JavaScript code

Share:
10,269
Admin
Author by

Admin

Updated on June 06, 2022

Comments

  • Admin
    Admin over 1 year

    I am using Prettier with format on save enabled but when I make any change in App.js and save it Prettier do destroy my code because it deals with it as plain javascript

    • Kaddath
      Kaddath almost 5 years
      I don't see react in the list of supported languages for prettier, maybe simply this?
    • Predrag Beocanin
      Predrag Beocanin almost 5 years
      React isn't a language, so that could be it!
    • kemotoe
      kemotoe almost 5 years
      It's common for another installed formatter to take precedence over prettier. Beautify is a common culprit.
    • serraosays
      serraosays almost 5 years
      I gave you a general answer since your question is so vague. Update it with more project information and I could provide a better answer.
    • MarsAndBack
      MarsAndBack almost 4 years
      kemotoe's comment is important. It's easy to install many 3rd-party extensions with overlapping functionality. Before anything else, one should inspect their VS Code extensions.
  • Predrag Beocanin
    Predrag Beocanin almost 5 years
    It's a personal preference, but most editors will behave better when it's just a .js file because it is just a .js file
  • MarsAndBack
    MarsAndBack almost 4 years
    So what happens when you're working in non-React JS files, where you might prefer other formatting?
  • Machado
    Machado about 3 years
    JS files doesn't have JSX HTML templates inside, so it's not just a JS file.
  • Muhammad Umer
    Muhammad Umer over 2 years
    you get emmet auto completes in nodejs that's what happens
  • 8bitIcon
    8bitIcon over 1 year
    @MarsAndBack You can create a directory /yourproject/.vscode/settings.json and paste above code there. Also make sure to add this directory in .gitignore