Follow these four steps to integrate esbuild into a Phoenix project:
1. Add dependency
In mix.exs:
def deps do
[
{:phoenix, github: "phoenixframework/phoenix", branch: "v1.5", override: true},
{:esbuild, "~> 0.10", runtime: Mix.env() == :dev}
]
end
2. Configure esbuild
In config/config.exs, define the default profile. Note the use of NODE_PATH to allow esbuild to find dependencies in your Elixir deps folder:
config :esbuild,
version: "0.25.5",
default: [
args: ~w(js/app.js --bundle --target=es2016 --outdir=../priv/static/assets),
cd: Path.expand("../assets", __DIR__),
env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)}
]
Note: Ensure the assets directory in priv/static is listed in the :only option for Plug.Static in your lib/my_app_web/endpoint.ex.
3. Enable Watch Mode for Development
In config/dev.exs, add the esbuild watcher to your watchers configuration:
esbuild: {Esbuild, :install_and_run, [:default, ~w(--sourcemap=inline --watch)]}
4. Configure Deployment
In mix.exs, add an assets.deploy alias to minify assets during deployment:
"assets.deploy": ["esbuild default --minify", "phx.digest"]
config :esbuild,
version: "0.25.5",
default: [
args: ~w(js/app.js --bundle --target=es2016 --outdir=../priv/static/assets),
cd: Path.expand("../assets", __DIR__),
env: %{"NODE_PATH" => Path.expand("../deps", __DIR\)}
]