Prettier : code formatting tool

When creating a pull request to our main Discourse repository, you might have noticed a bot sending this message in the comments:

We have been using Prettier on our codebase for a few weeks now, and are enforcing it in pull request too now.

What is prettier?

Prettier is an automatic code formatter. It will make sure all JS code follows established standards.

How to use it?

We recommend you set up your code editor to format on file save. We use the default prettier options.

It will depend of your editor but we recommend you use the prettier bin specified in Discourse’s package.json to ensure you use the same prettier version.

To do so run the following command: yarn install

Once installed, you can access it through: yarn run prettier make sure your editor/plugin/script is using this to run prettier, otherwise you might end up using a globally installed prettier which could be on a different version.

Atom

VIM

https://github.com/prettier/vim-prettier

Sublime Text

https://github.com/jonlabelle/SublimeJsPrettier

Emacs

https://github.com/prettier/prettier-emacs

Visual Studio Code

https://github.com/prettier/prettier-vscode

IntelliJ IDEA, RubyMine, WebStorm

This post is a wiki, feel free to edit with your specific configuration in your favorite editor.

Troubleshooting

  • I made a PR with a lot of files before configuring my editor, how can I run prettier on these files?

    git ls-files -m | grep -e ".*\.es6" -e ".*\.scss" | xargs prettier — --write

    This command will only work on modified files, if you have already multiple commits done in your branch you might want to reset soft to apply this, git reset --soft HEAD~2 if you have 2 commits for example, then commit this and then git push origin +your-branch-name to force update your github branch if it has already been pushed.

  • More advanced knowledge of Discourse linting can be found in this post: Code linting and formatting with prettier

29 Likes

Can we integrate/merge this with: Code linting and formatting with prettier

Not sure what to do about this, if your editor is configured you are not supposed to end up in this situation. So I will make a mix.

OK:

michael:~/prog/Discourse/discourse
± |master ✓| → yarn install
ERROR: [Errno 2] No such file or directory: 'install'

scratches head evidently I did something wrong?

1 Like

Never had this issue myself, but I’m on macOS (for a few more days :p) but I googled the error and found: https://stackoverflow.com/a/47680012

3 Likes