In Elixir, you can embed the contents of a configuration file directly into your module at compile time using module attributes. This is useful for static, environment-independent configs like JSON, YAML, or plain text files.

Suppose you have a file at config/my_config.json:

{
  "api_url": "https://example.com",
  "feature_enabled": true
}

You can load and embed it like this:

defmodule MyApp.Config do
  @external_resource "config/my_config.json"
  @config File.read!("config/my_config.json") |> Jason.decode!()

  def get_config, do: @config
end

What's happening?

  • @external_resource tells the compiler this module depends on the file.
  • @config is evaluated at compile time and stores the parsed content.
  • get_config/0 returns the embedded data at runtime—no file I/O needed after compilation.

When to use?

  • For static data that doesn’t change per environment.
  • To avoid runtime file reads and parsing.
  • To speed up access to configuration values.

This pattern is perfect for embedding static config into a release-ready binary with no external file dependencies.