Create a Mix Project and Run Elixir Code
April 27, 2017
Creating an Elixir project and running code is straightforward thanks to good conventions and solid tooling. It’s impressive when you consider what’s going on under the hood: compiling Elixir files into byte code that is then run on the 20-year-old, battle-proven Erlang VM.
In this video from our Elixir & OTP course, we walk through creating a mix project and the various ways to run Elixir files:
Here’s a quick recap of the commands we used in the video to run an Elixir file:
-
Run the
elixircommand with the relative path of the Elixir file:elixir lib/servy.exThe file gets compiled into bytecode (in memory) and then run on an Erlang virtual machine.
-
Fire up an
iex(Interactive Elixir) session and then use thechelper function to compile and run the file:iex iex> c "lib/servy.ex"The
chelper function compiles the given file in memory, the module (Servyin this case) is loaded into the session, and any code outside of the module is interpreted.To exit the
iexsession, pressCtrl+Ctwice. -
Alternatively, you can tell
iexto interpret an Elixir file while starting by passing the relative path of the file:iex lib/servy.ex -
When you start a standard
iexsession, it doesn’t know about the paths and dependencies of amixproject. So to start a session in the context of a project, you need to pass the-S mixoption:iex -S mix -
Finally, to recompile a module while in
iex, use therhelper function:iex> r ServyThis recompiles and reloads the given module, which is
Servyin this case.
Build a complete Elixir & OTP app from scratch!
Learn functional programming with Elixir as you build a concurrent, fault-tolerant application from scratch in our popular 6.5-hour Elixir & OTP course. By developing a real app with real code, you'll gain practical experience using all the facets of Elixir and OTP. Everything you need, assembled in the right order, and in one place! 👍