Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 3 — Tooling: From rebar3 to Mix

Mix is to Elixir what rebar3 is to Erlang — plus package management (Hex), documentation (ExDoc), formatting, and releases, all built in. This chapter gets you productive in one sitting; Chapter 09 goes deep on releases and running OTP apps.

From Erlang you know: the rebar3 → Mix mapping is nearly one-to-one, and the mental model transfers — project/0 ≈ rebar.config, aliases ≈ provider hooks, lib/mix/tasks/ ≈ plugins, _build/<env> ≈ rebar3’s profile directories. Two things are genuinely new: Hex (a package registry, so rebar3’s “fetch from git or nothing” is over), and tasks as first-class modules you can read. That second one is why Elixir tooling is legible in a way ~/.config/rebar3/rebar.config rarely is.

3.1 Command Map

Taskrebar3Mix
New projectrebar3 new app namemix new name
New OTP app w/ supervisionrebar3 new app name + boilerplatemix new name --sup
Fetch deps(automatic on compile)mix deps.get
Compilerebar3 compilemix compile
Run testsrebar3 eunit / ctmix test
Shellrebar3 shelliex -S mix
Format code(plugin)mix format
Docs(edoc plugin)mix docs (ex_doc)
Releaserebar3 releasemix release
Run tasksrebar3 <plugin-task>mix <task>

The pattern to notice: tasks that need plugins under rebar3 (formatting, docs) ship with Mix. Fewer decisions per project, more uniform codebases.

3.2 Your First Project, Step by Step

mix new hello --sup
cd hello

The --sup flag generates the application callback + root supervisor for you — no boilerplate copying from your last project.

Layout comparison:

hello/
├── lib/                    ← like Erlang src/, but the app entry lives here too
│   ├── hello/
│   │   └── application.ex  ← the {mod, {Mod, []}} + {applications, [...]} of .app.src, as a module
│   └── hello.ex            ← a default module
├── test/                   ← ExUnit tests (.exs)
│   └── hello_test.exs
├── mix.exs                 ← like rebar.config + .app.src combined
├── mix.lock                ← locked dep versions (created on first deps.get; commit it!)
└── .formatter.exs          ← formatter config

The two files that matter

lib/hello/application.ex — this is your OTP application callback. Read it with your application:start/2 knowledge:

defmodule Hello.Application do
  use Application                       # injects behaviour + defaults (Ch 05)

  @impl true
  def start(_type, _args) do
    children = [
      # Hello.Worker  ← your GenServers go here — plain child specs,
      #                 same {M, f, a} shape you know from supervisor docs
    ]

    Supervisor.start_link(children, strategy: :one_for_one, name: Hello.Supervisor)
  end
end

The .app file is generated, not written by you. After mix compile, _build/dev/lib/hello/ebin/hello.app contains:

{application,hello,[
  {modules,['Elixir.Hello']},
  {optional_applications,[]},
  {applications,[kernel,stdlib,elixir,logger]},
  {description,"hello"},
  {registered,[]},
  {vsn,"0.1.0"},
  {mod,{'Elixir.Hello.Application',[]}}
]}.

Two observations for an Erlang reader. First, same keys and semantics as the .app.src you hand-wrote — {mod, ...} is present only because mix.exs declared it. Second, applications is computed: it lists elixir because every Elixir app depends on it, plus whatever extra_applications and your deps contribute. There is no src/ directory, and no .app.src to keep in sync. Ch 08 §8.1 walks the rest of the build tree.

That generates exactly this supervision tree:

flowchart TD
    APP["hello app<br/>(mod callback in mix.exs)"] --> SUP["Hello.Supervisor<br/>one_for_one"]
    SUP --> W1["Hello.Worker<br/>(your GenServers)"]
    SUP --> W2["…more children"]

From Erlang you know: same supervision tree you’d write with supervisor:start_link. The child spec list replaces the .app mod boilerplate; strategies are identical (:one_for_one, :rest_for_one, :one_for_all). The name: option registers a local alias so you can address the supervisor by atom instead of pid — handy in Observer and RPC.

mix.exs — project metadata, deps, and compiler config in one place. Three functions matter:

defmodule Hello.MixProject do
  use Mix.Project

  def project do
    [
      app: :hello,                        # the OTP application name
      version: "0.1.0",
      elixir: "~> 1.15",                  # minimum Elixir requirement
      start_permanent: Mix.env() == :prod, # prod: VM dies if app dies
      deps: deps()
    ]
  end

  def application do                      # ← the .app.src equivalent
    [extra_applications: [:logger], mod: {Hello.Application, []}]
    #                                     ↑ mod: names your callback module
  end

  defp deps do
    [{:jason, "~> 1.4"}]                  # Hex packages; git/path also work
  end
end

The mapping to rebar3 concepts is direct: project/0 ≈ build config, application/0 ≈ .app.src (mod, extra_applications), deps/0 ≈ {deps, [...]} — except versions resolve from Hex with a lockfile.

Environments Play the Role of Profiles

rebar3 selects dependency sets and options through profiles (default, test, prod); Mix reaches the same place with environments plus the only: / runtime: dependency options:

rebar3MixNotes
rebar3 as prod releaseMIX_ENV=prod mix releaseenv-scoped _build subdir
profile-gated deponly: [:dev, :test]never compiled into prod
— (no analogue needed)runtime: falsecompiled, but not started
defp deps do
  [
    {:jason, "~> 1.4"},
    {:credo, "~> 1.7", only: [:dev, :test]},
    {:ex_doc, "~> 0.34", only: :dev, runtime: false}
  ]
end

mix.lock plays rebar.lock: commit it, review its diffs.

Daily loop

mix deps.get      # fetch from Hex (deps are in mix.exs)
mix compile       # compile to BEAM bytecode
mix test          # run ExUnit
iex -S mix        # interactive shell with the app started
mix format        # canonical formatting
mix hello.task    # run any custom task

Formatting: Zero Configuration Arguments

mix format ships canonical — the team debates nothing. All policy lives in .formatter.exs:

[
  import_deps: [:ecto],
  inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"],
  line_length: 98
]

Enforce in CI with mix format --check-formatted — nonzero exit on drift, no plugin required.

One migration tool worth knowing on day one, because it rewrites files rather than complaining:

mix format --migrate

Verified on a file containing def a, do: 'charlist':

# before
def a, do: 'charlist'
# after
def a, do: ~c"charlist"

That is what converts deprecated charlist literals ('…' → ~c"…") and unless expressions in bulk — see Ch 02 §2.7 on the 1.17+ charlist deprecation. It changes the AST, so the docs’ own advice applies: run it in its own commit and review the diff before committing, especially in a macro-heavy project (--migrate needs an .formatter.exs with :inputs to know what to touch).

Docs Flow Straight to hexdocs

Write @moduledoc / @doc (persisted into .beam documentation chunks — see §2.1’s attribute notes), then:

mix docs               # generates doc/ via ex_doc — edoc's successor
mix hex.publish        # publishing a package pushes docs to hexdocs.pm too
mix hex.docs publish   # or push docs for an already-published release

Consumers read the result at hexdocs.pm/your_package — zero extra infrastructure, unlike standing up an edoc site.

flowchart LR
    NEW["mix new --sup"] --> EDIT["edit lib/*.ex"] --> COMP{"mix compile"}
    COMP -->|"warnings/errors"| FIX["fix · recompile"]
    FIX --> COMP
    COMP -->|ok| TST["mix test"]
    TST -->|"red"| EDIT
    TST -->|"green"| SH["iex -S mix<br/>dbg · h · i helpers"]
    SH --> FMT["mix format"] --> REL["MIX_ENV=prod mix release"]

IEx Helpers You’ll Use Constantly

Start the shell and lean on these (all built into IEx):

iex> h Enum.reduce      # documentation for anything — no browser needed
iex> i self()           # introspect any term's type/implementation/raw repr
iex> recompile()        # after editing source without leaving iex
iex> Hello.Math.add(1, 2)
3

# Kernel's dbg/1 — inspect a pipeline step by step:
iex> dbg(1..5 |> Enum.map(&(&1 * 2)) |> Enum.sum())

dbg/1 prints the code with each intermediate value plus the final result — the fastest way to see what a pipe chain is doing:

1..5 |> Enum.map(&(&1 * 2)) |> Enum.sum()
#⇒ [1, 2, 3, 4, 5] |> Enum.map(&(&1 * 2))
#⇒ [2, 4, 6, 8, 10] |> Enum.sum()
#⇒ 30

Also worth adopting early: timeouts accept readable durations via to_timeout/1 (to_timeout(hour: 2) instead of magic milliseconds) — handy for Process.send_after/3 and GenServer timeouts.

Aliases and Custom Tasks Replace rebar3 Plugins

rebar3 plugins mostly existed to glue command sequences together. Mix covers both halves natively. Half one, aliases — named pipelines of tasks in mix.exs; entries run in order, failing fast:

def project do
  [
    # ...,
    aliases: aliases()
  ]
end

defp aliases do
  [
    setup: ["deps.get", "compile"],
    check: ["format --check-formatted", "test", "credo"]
  ]
end

Now mix check runs the whole gate — the provider-chain feel of rebar3 hooks, minus the configuration ceremony. It does require the credo dep from step 1 above; without it the credo task is simply not defined. Half two, custom tasks: drop a module under lib/mix/tasks/ whose name descends from Mix.Tasks:

# lib/mix/tasks/hello.greet.ex — file name mirrors the task name
defmodule Mix.Tasks.Hello.Greet do
  use Mix.Task

  @shortdoc "Greets whoever you pass"

  @impl Mix.Task
  def run(args) do
    Mix.shell().info("hello, #{Enum.join(args, " ")}")
  end
end
mix hello.greet ada grace   #=> hello, ada grace
mix help hello.greet        # @shortdoc shows up in the listing

That is the entire plugin mechanism — no plugin registration in .app.src, no provider wiring.

3.3 Tests: ExUnit vs EUnit/Common Test

defmodule Hello.MathTest do
  use ExUnit.Case, async: true       # concurrent suite — safe because processes isolate

  test "add returns the sum" do
    assert Hello.Math.add(1, 2) == 3
  end

  test "pattern matching failures" do
    assert {:error, :enoent} = File.read("nope.txt")   # assert MATCHES the pattern
  end
end

Reading guide:

  • assert pattern = value asserts that the match succeeds AND binds — failures print both sides. This makes most tests one line.
  • async: true runs suites concurrently on separate processes — safe by default because processes are isolated. (Shared resources — DBs, ports — need sandboxing; Ch 11 shows Ecto’s approach.)
  • Setup/teardown via setup blocks instead of init/end_per_testcase.
  • Property testing: StreamData fills the QuickCheck niche.
  • Process-based tests (like Common Test’s process scenarios) use start_supervised!/1 — starts a child under a test-owned supervisor that shuts down cleanly after each test.

Run it:

mix test                     # all
mix test path/to/file.exs    # one file
mix test --trace             # no timeouts, sequential (debug async issues)
mix test --failed            # re-run only what last failed
mix test --cover             # built-in line coverage summary

Two more that close loops Chapter 01 opened:

  • Doctests. Every iex> block in a @doc/@moduledoc becomes a real test — but only if you ask for it, once per module:

    defmodule Hello.MathTest do
      use ExUnit.Case, async: true
      doctest Hello.Math     # runs every example in Hello.Math's docs
    end
    

    If a documented example is wrong, mix test says so. That is the entire mechanism behind “docs are executable” — and the reason the examples in this book carry iex> prompts.

  • xref / dialyzer. Your rebar3 instincts carry over with different names:

    rebar3Mix
    rebar3 xrefmix xref graph --format dot / mix xref callers|callees
    rebar3 dialyzermix dialyzer (via dialyxir), plus Elixir’s own gradual types (Ch 07)
    rebar3 eunitmix test
    rebar3 ctmix test + start_supervised!/1 (Common Test’s process scenarios)

3.4 Releases

mix release produces a self-contained, OTP-native release — same bin/app interface you know from rebar3 release:

MIX_ENV=prod mix release
_build/prod/rel/hello/bin/hello start     # foreground
_build/prod/rel/hello/bin/hello daemon    # background

Supports runtime config (config/runtime.exs), overlays, and hot upgrades via the standard relup tooling when needed. The full walkthrough — release anatomy, daemon operation, remote shells, and step-by-step hot upgrades — is Chapter 09.

3.5 Calling Erlang from Elixir (and vice versa)

Interop is zero-friction — every Erlang library is available immediately:

:lists.max([3, 1, 2])              #=> 3
:ets.new(:cache, [:set, :named_table])
:gen_server.start_link(:my_mod, arg, [])   # Erlang modules are lowercase atoms
{:ok, pid} = :file.open("data.txt")

Erlang libraries are ordinary Mix dependencies — same registry, different spelling of the source:

def deps do
  [
    # a Hex package that happens to be written in Erlang
    {:cowboy, "~> 2.10"},           # called as :cowboy.start_clear/3
    # an Erlang library straight from git
    {:my_erl_lib, git: "https://github.com/org/lib.git", tag: "v1.0.0"},
    # a sibling checkout in your working tree
    {:local_lib, path: "../local_lib", override: true}
  ]
end

Mix compiles Erlang sources in the dependency just as it compiles Elixir ones, so you get .beam files and a working .app file with no extra setup. The one thing to know is that the application starts under an Erlang-style atom: :cowboy, :my_erl_lib — not Cowboy, MyErlLib.

Any existing Erlang application can be added as a dependency and used directly — no wrapper needed until you want an idiomatic Elixir API over it. In practice teams wrap gradually: raw :module.fun calls first, then an alias-heavy facade module, then (sometimes) a proper Elixir API package.

3.6 Step-by-Step Exercise

  1. Create: mix new portme --sup
  2. Add a supervised GenServer that holds state (Ch 05 shows idiomatic style).
  3. Call an Erlang function inside it (:calendar.system_time_to_rfc3339/2).
  4. Write an ExUnit test asserting its state transitions.
  5. Build a release and run it: MIX_ENV=prod mix release && ...start.
  6. Bonus: add {:credo, "~> 1.7", only: [:dev, :test]} and run mix credo.

3.7 Umbrella Projects: rebar3 Sub-Apps, Unified

If you maintain a rebar3 repository holding several OTP apps under apps/, Mix umbrellas will feel immediate:

mix new company --umbrella
cd company/apps && mix new billing --sup && mix new web
company/
├── mix.exs            ← umbrella root: shared version + shared deps only
└── apps/
    ├── billing/       ← a COMPLETE mix project (own mix.exs, own app)
    └── web/           ← depends on :billing via a normal deps entry

Root-level commands fan out to every child — mix test, mix compile, and mix format all recurse; mix cmd --app web ... targets a single child. Inter-app dependencies resolve locally first, mirroring how rebar3 orders sub-app builds. Differences worth knowing: children share one _build and one deps/ (faster, less disk), yet each still compiles to its own .beam set and can be released individually or as one combined release.

Explore More

  • Mix docs — environments, dependencies, aliases, configuration deep-dive
  • mix new task — all generator flags including --umbrella
  • ExUnit docs — tags, contexts, capture_log, and the full assertion library
  • Hex packages — browse by “downloads” to find the battle-tested library for any job
  • mix format task — the full option list, including --migrate and --check-formatted
  • Erlang/OTP Design Principles — the release-handling and application-controller rules that application.ex implements for you
  • Exercise idea: recreate your favorite rebar3 plugin’s functionality as a custom Mix task (§9.3 of Ch 09 shows how)

Checkpoint

  1. Which file plays the role of .app.src’s mod declaration?
  2. How do you start your app + shell at once?
  3. How would you depend on an existing Erlang hex/repo package?
  4. What does --sup save you writing, and where does that code live?
Answers
  1. mod: {Hello.Application, []} in application/0 inside mix.exs, implemented by Hello.Application.start/2.
  2. iex -S mix
  3. Add it to deps() — Hex packages or git repos work regardless of whether they’re written in Erlang or Elixir.
  4. The Application behaviour module and root supervisor boilerplate; generated at lib/hello/application.ex with children wired into Supervisor.start_link/2.

Next: Chapter 4 — Pipes, Enum & Stream