TExcelTAD
Home › Elixir › Elixir Mix & Projects

Elixir Mix & Projects

Scripts are great for learning, but real applications are Mix projects. Mix is Elixir's build tool: it creates projects, compiles code, fetches dependencies from Hex (the package registry), runs tests, and starts your application. Everything in this lesson is run in a terminal on your own machine.

Creating a project

bash
$ mix new inventory --sup
* creating README.md
* creating .formatter.exs
* creating .gitignore
* creating mix.exs
* creating lib
* creating lib/inventory.ex
* creating lib/inventory/application.ex
* creating test
* creating test/test_helper.exs
* creating test/inventory_test.exs

--sup adds an Application module with a supervision tree. The layout:

Path Contents
mix.exs project definition: name, version, Elixir requirement, dependencies
lib/ your application code (.ex files), one module per file by convention
lib/inventory/application.ex starts the root supervisor
test/ ExUnit tests (*_test.exs)
config/ optional config.exs, runtime.exs and per-environment files
_build/ compiled .beam files (generated, not committed)
deps/ downloaded dependencies (generated)
mix.lock exact dependency versions (commit this)

mix.exs

elixir
defmodule Inventory.MixProject do
  use Mix.Project

  def project do
    [
      app: :inventory,
      version: "0.1.0",
      elixir: "~> 1.19",
      start_permanent: Mix.env() == :prod,
      deps: deps()
    ]
  end

  def application do
    [extra_applications: [:logger], mod: {Inventory.Application, []}]
  end

  defp deps do
    [
      {:jason, "~> 1.4"},
      {:req, "~> 0.5"},
      {:credo, "~> 1.7", only: [:dev, :test], runtime: false}
    ]
  end
end

Version requirements

Dependencies use semantic versioning requirements. ~> ("compatible with") is the most common: ~> 1.4 means >= 1.4.0 and < 2.0.0, while ~> 1.4.2 means >= 1.4.2 and < 1.5.0. Elixir's built-in Version module implements exactly these rules, so you can try them:

elixir · try it yourself
checks = [
  {"1.4.0", "~> 1.4"},
  {"1.9.3", "~> 1.4"},
  {"2.0.0", "~> 1.4"},
  {"1.4.9", "~> 1.4.2"},
  {"1.5.0", "~> 1.4.2"},
  {"0.5.1", ">= 0.5.0 and < 0.6.0"}
]

for {version, requirement} <- checks do
  IO.puts("#{String.pad_trailing(version, 6)} #{String.pad_trailing(requirement, 22)} #{Version.match?(version, requirement)}")
end

IO.inspect(Version.compare("1.19.0", "1.9.0"))
IO.inspect(Version.parse!("2.1.0-rc.1").pre)
1.4.0  ~> 1.4                 true
1.9.3  ~> 1.4                 true
2.0.0  ~> 1.4                 false
1.4.9  ~> 1.4.2               true
1.5.0  ~> 1.4.2               false
0.5.1  >= 0.5.0 and < 0.6.0   true
:gt
["rc", 1]

Note the comparison: 1.19.0 is greater than 1.9.0, because each part is compared as a number, not as text.

Everyday Mix commands

Command What it does
mix deps.get download dependencies listed in mix.exs
mix compile compile the project (other tasks do this automatically)
mix test run the test suite
mix format format all code according to .formatter.exs
iex -S mix start IEx with the project loaded
mix run --no-halt run the application
mix help list every available task
mix hex.info jason information about a package
mix release build a self-contained release for deployment

Libraries can add tasks too: mix phx.server (Phoenix), mix ecto.migrate (Ecto), mix credo (linter), mix dialyzer.

Environments and configuration

Mix runs in an environment: :dev (default), :test (used by mix test) or :prod, chosen with MIX_ENV=prod. Configuration lives in config/:

elixir
# config/config.exs (compile time, all environments)
import Config
config :inventory, low_stock_threshold: 5
import_config "#{config_env()}.exs"

# config/runtime.exs (read when the system starts: secrets, URLs)
import Config
config :inventory, api_key: System.fetch_env!("INVENTORY_API_KEY")

Code reads configuration with Application.get_env/3 or Application.fetch_env!/2. The values are stored per application, which you can simulate in a script with Application.put_env/3:

elixir · try it yourself
Application.put_env(:inventory, :low_stock_threshold, 5)

defmodule Inventory.Stock do
  def low?(qty), do: qty < Application.fetch_env!(:inventory, :low_stock_threshold)
  def warehouse, do: Application.get_env(:inventory, :warehouse, "main")
end

IO.inspect(Inventory.Stock.low?(3))
IO.inspect(Inventory.Stock.low?(12))
IO.inspect(Inventory.Stock.warehouse())
true
false
"main"

Tip: Read configuration at runtime (inside functions, as above), not in module attributes (@threshold Application.get_env(...)), which would freeze the value at compile time.

Scripts with dependencies: Mix.install

For quick experiments and Livebook notebooks, a single .exs file can install packages itself:

elixir
Mix.install([{:req, "~> 0.5"}])

Req.get!("https://api.github.com/repos/elixir-lang/elixir").body["stargazers_count"]
|> IO.inspect()

The examples on this site don't use Hex packages, so they all run with plain elixir main.exs.

Umbrella projects and releases

  • An umbrella project (mix new shop --umbrella) holds several applications in apps/ that are developed together.
  • A release (mix release) bundles your compiled code, its dependencies and the Erlang runtime into one directory you can copy to a server and start with bin/inventory start.

Test yourself

Which versions satisfy ~> 2.3?

  1. Only 2.3.x
  2. >= 2.3.0 and < 3.0.0
  3. Any 2.x or 3.x
  4. Exactly 2.3.0

Which command starts IEx with your project's code loaded?

  1. iex mix
  2. mix iex
  3. iex -S mix
  4. mix run iex

Which file should you commit to pin exact dependency versions?

  1. deps/
  2. _build/
  3. mix.lock
  4. .formatter.exs