What’s the difference between .ex and .exs file extensions

When it comes to Elixir you’ll notice there are two file extensions, namely .ex and .exs.

Each extension serves its own purpose:

  • .ex is used for compilation, while
  • .exs is used for scripting.

Compilation (.ex)

Generally we write our modules in separate files that then get compiled — thereby allowing reuse. We compile our files by running elixirc greet.ex

That will generate another file, Elixir.Greet.beam. It contains the bytecode for our module. Starting iex in the same directory also makes our module definition available for use.

Firing up iex let’s us do:

iex(1)>
Greet.sayHello
hello
:ok

Scripting (.exs)

Elixir files using the .exs extension are treated in the same way as .ex files. The only difference is that while both will be loaded into memory, the .exs file won’t have its bytecode written to file i.e. no Elixir.Greet.beam file.

Example:

hello.exs contains: elixir IO.puts "Hello there!"

We execute our script by running elixir hello.exs:

This brings us to the c/1 iex helper. When you’re in iex you can run c "yourfilename.exs" to load the code or module into memory, thereby making it available to use.

Hope this helped explain the core differences between the file extensions.

See you soon.


Originally published at justmegareth.com on April 13, 2017.