r/VisualStudioCode • • Jan 22 '23

How do I add semicolons in Javascript?

I've been learning Javascript for 10 weeks now.

I was told semicolons were optional.

I've got in a habit of leaving them out everywhere!

Now... I learn that it is highly advisable to add semicolons 🤦‍‍

I'm finding it hard to kick the first habit of leaving out semicolons!

What can I use to add semicolons automatically?

I've got the standard code prettier extension. I think I've got it tweaked so that braces appear on a new line. I'm guessing it will be the same extension that I need to use to add semicolons?

Thanks.

0 Upvotes

6 comments sorted by

View all comments

Show parent comment

1

u/zombarista Jan 27 '23

I usually run prettier wherever my package.json file is, but you only need to run it in a parent directory of your js... the glob **/*.js will go through all subdirectories, find JS files, and format them in place...

so if your project looks like this...

project/
   package.json
   src/
      component/
         component.js

You could run the prettier command in project/ or src/ or component/

I recommend setting up vscode to use prettier as its code formatter. Then it's just a matter of using Right Click > Format document (or Shift-Alt-F on Windows) to format whatever file you're looking at. There's a plugin in the Marketplace that will set that up automatically for you.

Also, if running prettier gives you fits, it's probably because it isn't on your PATH. Use `npx` to fix this issue and just type `npx prettier --write **.*.js` and it will resolve the PATH issue for you.

Happy coding!