Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 48 ยท Protocols, Errors and Tooling

Mix: Creating and Managing Projects

Learn how Mix creates Elixir projects, what mix.exs contains, how dependencies and Hex work, and how environments and releases fit in.

So far you have written single files and small snippets. Real programs have many modules, tests, third-party libraries and different settings for development and production. Mix is the build tool that ships with Elixir and takes care of all of this: it creates projects, compiles code, runs tests, fetches dependencies and builds releases.

Elixir does not run on this site, so every Elixir and shell block in this lesson is read-only. The two editors use JavaScript to imitate two small rules of Mix (version requirements and file naming) so you can experiment with them. Mix is the tool you will use for every lesson from here on, including the typespecs you just met and testing with ExUnit later.

What Mix does

Create mix new builds a project skeleton.
Compile mix compile turns lib/ into BEAM files.
Dependencies mix deps.get fetches libraries from Hex.
Test mix test runs everything in test/.

One tool for the whole project life cycle.

1 / 2

Creating a project

Run mix new with a name in snake_case:

Terminal
mix new shop
cd shop

Mix creates a small folder tree:

TEXT
shop/
  .formatter.exs
  .gitignore
  README.md
  mix.exs
  lib/
    shop.ex
  test/
    shop_test.exs
    test_helper.exs

The lib/ folder holds your application code, test/ holds tests, and mix.exs describes the project. .formatter.exs configures mix format, which rewrites files in the standard style. Add --sup (mix new shop --sup) when the project should start its own supervision tree, which you will need after Supervisors.

The first module is already there:

ELIXIR
defmodule Shop do
  @moduledoc """
  Documentation for `Shop`.
  """

  def hello do
    :world
  end
end

Run mix test and Mix compiles the project, then runs the generated test, which checks that Shop.hello() returns :world.

Files and module names

Elixir does not force a file to match its module, but everyone follows a convention: the module Shop.Billing.Invoice lives in lib/shop/billing/invoice.ex. Names turn from CamelCase into snake_case, and the dots become folders. One file usually holds one module, and Mix compiles all .ex files under lib/ for you; there is no import list to maintain.

Files that end in .exs are scripts. Mix does not compile them into lib/; it evaluates them when needed. That is why mix.exs, config/*.exs and test files use the .exs extension.

JS Module name to file path (JavaScript stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Note the last line of output: a run of capitals like HTTP is awkward to convert. The real tools (such as the code generators Phoenix ships) handle acronyms with their own rules, so this stand-in only shows the shape of the idea.

Reading mix.exs

mix.exs is itself Elixir code. It defines a module with a project/0 function that returns a keyword list:

ELIXIR
defmodule Shop.MixProject do
  use Mix.Project

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

  def application do
    [
      extra_applications: [:logger]
    ]
  end

  defp deps do
    [
      {:jason, "~> 1.4"},
      {:ex_doc, "~> 0.34", only: :dev, runtime: false}
    ]
  end
end
  • app is the name of your application, an atom.
  • elixir is the range of Elixir versions the project supports.
  • start_permanent makes the whole VM stop if the application crashes, which you want in production.
  • application/0 lists what has to be running. extra_applications: [:logger] adds the Logger from the standard distribution. With --sup, a mod: entry names the module that starts your supervision tree.
  • deps/0 lists dependencies.

Dependencies and Hex

Libraries are published on Hex, the package manager of the Erlang and Elixir world. A dependency is a tuple of the package name and a version requirement, with optional settings such as only: :dev. After editing deps/0, run:

Terminal
mix deps.get

Mix downloads the packages into deps/ and records the exact versions in mix.lock. Commit mix.lock so that everyone, including your servers, builds with the same versions. Other useful commands are mix deps.update jason and mix deps.tree.

The version requirement "~> 1.4" is called the pessimistic operator. It allows any version that is at least 1.4.0 but below 2.0.0. The longer form "~> 1.4.2" allows 1.4.2 and later patches, but stays below 1.5.0. In other words, the last number you write is the one that may grow. You can also write ">= 1.0.0", "== 1.4.0" or combine with and/or.

JS How ~> picks versions (JavaScript stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real Mix uses full semantic-version parsing, so treat this as a model of the rule, not a replacement.

Environments and configuration

Mix runs in one of three environments, stored in the MIX_ENV variable: dev (the default), test (set automatically by mix test) and prod. Code can ask which one is active with Mix.env(), but only at build time: Mix itself is usually not available inside a release, so avoid calling it at run time.

Configuration lives in the config/ folder. A common layout is config/config.exs for shared settings, one file per environment, and config/runtime.exs, which is evaluated when the application starts and is the right place to read secrets from environment variables. Releases, Config and Deployment goes deeper.

ELIXIR
# config/runtime.exs
import Config

if config_env() == :prod do
  config :shop, database_url: System.fetch_env!("DATABASE_URL")
end

Dependencies can be limited to an environment, as ex_doc is above with only: :dev, so test or production builds do not carry them.

Everyday commands

Terminal
mix compile            # compile the project
mix test               # run tests
mix format             # format all files
mix deps.get           # fetch dependencies
iex -S mix             # open IEx with your project loaded
MIX_ENV=prod mix compile
mix help               # list every task

iex -S mix is the one you will use most when exploring: you get the interactive shell with all of your modules available, as you saw in Installing Elixir and Using IEx.

Releases in one paragraph

A release is a self-contained package of your compiled code, its dependencies and the Erlang runtime. You build it with MIX_ENV=prod mix release, copy the result to a server and start it with a script, with no Elixir or Mix installed there. Releases support runtime configuration, remote shells and hot code upgrade hooks. The later lesson on deployment covers them properly.

Mix tasks are plain Elixir modules named Mix.Tasks.Something, so you can write your own with use Mix.Task. Large projects use this to script database setup, data imports and similar chores.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where would the module Shop.Billing.Invoice normally live?

    By convention names become snake_case and dots become folders under lib/, with the .ex extension for compiled code.
  2. 2. Which versions does the requirement "~> 1.4.2" allow?

    The last number you write may grow. With three parts the patch level can grow; with ~> 1.4 the minor level can grow instead.
  3. 3. Why should you commit mix.lock?

    The lock file records the exact version of each dependency that mix deps.get resolved, so builds are repeatable.
  4. 4. Which file is the right place to read secrets from environment variables when a release starts?

    runtime.exs is evaluated when the application boots, so it sees the environment of the running server rather than of the build machine.

Summary

  • Mix creates, compiles, tests and packages Elixir projects; mix new name generates the skeleton.
  • Application code goes in lib/ as .ex files; scripts, config and tests use .exs.
  • mix.exs holds the project settings, the application/0 callback and the deps/0 list.
  • Dependencies come from Hex; mix deps.get fetches them and mix.lock pins versions.
  • ~> allows growth only in the last number you write.
  • Mix has dev, test and prod environments, and config/runtime.exs is for run-time settings.
  • mix release builds a self-contained package for production.

Next up: Processes and Message Passing.