Basics

Elixir Running Code

Running Elixir Code

Elixir code runs via iex or mix with .ex or .exs files.

Introduction to Running Elixir Code

Elixir, a dynamic and functional language built on top of the Erlang VM, provides two main ways to run your code: via the interactive shell (iex) or using the build tool (mix). Understanding how to execute Elixir scripts and manage projects is crucial for effective development.

Running Elixir Code with iex

The iex (Interactive Elixir) shell allows you to evaluate expressions in real-time, making it an excellent tool for experimentation and debugging. To start iex, simply type the following command in your terminal:

Once inside the iex shell, you can execute Elixir expressions directly. Let's try a simple calculation:

To run a script within iex, you can use the c command followed by the file name. Ensure the file has a .exs extension:

Running Elixir Code with mix

mix is a crucial tool for managing Elixir projects. It provides tasks for creating projects, compiling code, running tests, and more. To execute scripts using mix, your code should typically be in a project structure. Here’s how to create a new project:

This command generates a new directory with a basic project structure. Navigate into your project directory and use the mix run command to run your application:

The mix run command executes the lib/my_project.ex file. You can modify this file or create new ones to expand your application.

Understanding .ex and .exs Files

Elixir scripts typically have two file extensions: .ex and .exs. The .ex files are compiled, while .exs files are meant for scripting and are not compiled. Use .exs for tasks like scripts and testing, and .ex for defining modules and functions that are part of your application.

Conclusion

Mastering how to run Elixir code using iex and mix is fundamental for any Elixir developer. These tools provide flexibility and efficiency in both scripting and building robust applications. Continue exploring to deepen your understanding and enhance your Elixir development workflow.