ðĶMix
Mix is Elixir's built-in build tool. Build tools are useful for managing the structure of a project, handling the build process, downloading external packages, and even create custom scripts to handle parts of your project for you. Other build tools include npm
in Javascript and Gradle in Java.
Getting started
Mix is a relatively opinionated build tool. This means that Mix provides a project structure for you. This is particularly useful for people starting out so they do not need to think too much about how to structure their projects (compared to languages like Go that have a package management tool but no fixed project structure).
To create a project with Mix, you will use the mix new
command (should already be installed when you installed Elixir):
Mix will create a new folder kv/
with the following structure:
Project structure
The default project structure includes basic files like README.md
and .gitignore
and additional Elixir specific files and folders.
lib/
The lib/
folder contains the code that you will write. Notice that when you created the project, you specified the module name as KV
. This should be the root module of your project.
The initial file lib/kv.ex
will be the root file that contains the KV
module and any related functions under this module. If you are creating any sub-modules, you will create a folder lib/kv/
and add the folders/files there.
Where utils.ex
looks like this:
test/
Mix uses ExUnit (Elixir's testing framework) to perform unit testing. These unit tests are stored under the test/
folder and the folder follows the same structure as the lib/
folder. Test files are appended with _test
and run as .exs
files instead of .ex
.
You can run the tests via
This guide will not go into the full details of unit testing in Elixir.
mix.exs
This is the equivalent of package.json
or build.gradle
where it contains the specific instructions and packages to include for the project.
For now, the key function you should be concerned about is deps
which specifies the dependencies of the project. The packages of the project are specified as a list of tuple.
Compiling the project
Mix fixes this by helping us with the compilation process:
Then, to run IEx with the compiled files, you can use:
Creating a long running application
You may not want your application to only be runnable from IEx. If you wish to create a long running application, you will have to use the Application
module.
First, create a file application.ex
under lib/kv/
and add the following contents to the file:
Then, go to mix.exs
and add the following line to the array returned by the application
function:
This allows Mix to know to run the start/2
behavior under KV.Application
module when you use:
You should see Hello World
printed as specified by start/2
.
Last updated