dwyl / learn-elixir

:droplet: Learn the Elixir programming language to build functional, fast, scalable and maintainable web applications!
1.62k stars 109 forks source link

Elixir Formatter > mix format command > .formatter.exs config #89

Closed nelsonic closed 6 years ago

nelsonic commented 6 years ago

iPropose adding this to the readme:


In Elixir version 1.6 the mix format task was introduced. It is a built-in way to format your Elixir code according to the community-agreed standard. Which means all code will look consistent across projects (personal, client & hex.pm packages) which makes learning faster and maintainability easier! At present, using the formatter is optional, however most Elixir projects have adopted it.

To use the mix task in your project, you can either check files individually, e.g:

mix format path/to/file.ex

Or you can define a pattern for types of files you want to check the format of:

mix format "lib/**/*.{ex,exs}"

To check all the .ex and .exs files in the lib/ directory. Having to type this pattern each time you want to check the files is tedious. Thankfully you can define the pattern in a config file and then simply run mix format and the pattern is read from the file.

In the root of your Elixir project, create a .formatter.exs config file and paste the following:

[
  inputs: ["mix.exs", "{config,lib,test}/**/*.{ex,exs}"]
]

Now when you run mix format it will check the mix.exs file and all .ex and .exs files in the config, lib/ and test directories.

This is the most common pattern for running mix format. Unless you have a reason to "deviate" from it, it's a good practice to follow.

There is an easy way to "fix" any Elixir code that does not meet the formatting guidelines, simply run:

mix format

And your code will be cleaned up.


Anyone object to me adding this? (or feel free to edit/improve the copy...)

finnhodgkin commented 6 years ago

Oo love that autoformatting is becoming the norm. Might be worth also including links to the atom and vscode addons for fix on save formatting.

nelsonic commented 6 years ago

@finnhodgkin great shout! adding this to my PR now. 👍

junjizhi commented 6 years ago

mix format will only respect .formatter.exs settings when it is running at the same folder (project root) with the settings file. If we run mix format file.ex in a subfolder, then it ignores the settings and use default ones. Is this intended? It would be nice to traverse to upper folder to look for formatter.exs. Should we file a bug/feature for this?