Elixir: When to use .ex and when .exs files

Elixir's documentation states that

In addition to the Elixir file extension .ex, Elixir also supports .exs files for scripting. Elixir treats both files exactly the same way, the only difference is in intention. .ex files are meant to be compiled while .exs files are used for scripting, without the need for compilation.

But I'm still not sure when to use which file type. What are the downsides and the purpose of .ex and .exs?


Solution 1:

.ex is for compiled code, .exs is for interpreted code.

ExUnit tests, for example, are in .exs files so that you don't have to recompile every time you make a change to your tests. If you're writing scripts or tests, use .exs files. Otherwise, just use .ex files and compile your code.

As far as pros/cons, interpretation will take longer to execute (as elixir has to parse, tokenize, etc.), but doesn't require compilation to run. That's pretty much it - if the flexibility of running scripts is more important than optimized execution time, use .exs. Most of the time, you'll use .ex.

Solution 2:

Elixir will compile the whole .ex file.

.exs files are compiled as well but are meant to be executed when invoked. So, most use cases of .exs files are to execute code immediately when called. Think of using .exs files for testing, migrating data and running scripts. Think of .ex files as being used for your application's main business logic.

Consider this example

.ex sample

sum.ex:

defmodule Sum do
  def add(a, b) do
    a + b
  end
end
$ iex sum.ex
...

Interactive Elixir (1.9.4) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> Sum.add(1, 2)
3

.exs sample

sum.exs:

defmodule Sum do
  def add(a, b)  do
    a + b
  end
end

#within same file

IO.puts "The sum of 3 + 2 is: #{inspect Sum.add(3, 2)}"
$ elixir sum.exs
The sum of 3 + 2 is: 5