LoginSignup
13
0

More than 1 year has passed since last update.

今日のElixirSchoolメモ9「Mix」

Last updated at Posted at 2022-12-09

Elixir Schoolの勉強メモです。

Mix

mixは、RubyでいうところのBundlerとRubyGems、Rakeが組み合わさったもの。
mix helpで機能を確認できる。

新しいElixirプロジェクト作成

mix newコマンドで新しいElixirプロジェクトを立ち上げることができる。
プロジェクトのフォルダ構成と必要なボイラープレート(決まりきったソースコード断片)が生成される。

mix new example
* creating README.md
* creating .formatter.exs
* creating .gitignore
* creating mix.exs
* creating lib
* creating lib/example.ex
* creating test
* creating test/test_helper.exs
* creating test/example_test.exs

Your Mix project was created successfully.
You can use "mix" to compile it, test it, and more:

    cd example
    mix test

mix.exs

アプリケーションや依存関係、環境、バージョンについて設定をするファイル。

defmodule Example.MixProject do
  use Mix.Project

  def project do
    [
      app: :example, # アプリケーションの名前の定義
      version: "0.1.0",
      elixir: "~> 1.13",
      start_permanent: Mix.env() == :prod,
      deps: deps()
    ]
  end

  # Run "mix help compile.app" to learn about applications.
  def application do
    [
      extra_applications: [:logger]
    ]
  end

  # Run "mix help deps" to learn about dependencies.
  # 依存関係
  defp deps do
    [
      # {:dep_from_hexpm, "~> 0.3.0"},
      # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
    ]
  end
end

iex -S mix

-S mixオプションで、インタラクションモードに入る前にMixを走らせることができる。
コンパイルされたアプリケーションとともに新しいiexセッションを開始することができる。

iex -S mix
Erlang/OTP 25 [erts-13.0] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit:ns]

Compiling 1 file (.ex)
Generated example app
Interactive Elixir (1.13.4) - press Ctrl+C to exit (type h() ENTER for help)

コンパイル

mixは賢く、必要に応じてコードの変更をコンパイルしてくれるが、明示的にコンパイルするときはmix compileをプロジェクト直下のディレクトリで実行する。

コンパイルする際、mixは_buildディレクトリを生成する。_build内部を参照すると、コンパイルされたアプルケーション_build/dev/lib/example/ebin/example.appがある。

依存関係の管理

新しい依存関係を追加するには、まずmix.exsdeps内に追加する。
依存関係のリストは、パッケージ名のアトムと、バージョンを表す文字列、1つの任意的な値(オプション)を持つタプルで成り立つ。

def deps do
  [
    {:phoenix, "~> 1.1 or ~> 1.2"},
    {:phoenix_html, "~> 2.3"},
    {:cowboy, "~> 1.0", only: [:dev, :test]},
    {:slime, "~> 0.14"}
  ]
end

依存関係を定義したら、パッケージを取り込む。

mix deps.get

環境

  • :dev
    • 初期状態での環境
  • :test
    • mix testで用いられる環境
  • :prod
    • アプリケーションを製品に出荷するときに用いられる環境

現在の環境はMix.envで取得できる。
この環境はMIX_ENV環境変数によって変更できる。

MIX_ENV=prod mix compile
13
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
0