Add Sass to Phoenix 1.6 with Esbuild
- 2 minutes read - 238 wordsIf you are starting a new project with The Phoenix Framework version 1.6, you’ll notice there has been a change with regard to asset handling. Chris McCord and The Phoenix Team have made the choice to move away from WebPack and start using Esbuild to deal with the Javascript files. One side effect of this is you lose the ability to use Sass files by default. Have no fear, there’s a way to add Sass back into your project.
You just need to add the DartSass library to your project and configure it. The steps are in the github readme file. I’ll lay them out here for convienence.
- Add DartSass as a dependency in your mix.exs file:
def deps do
[
{:phoenix, "~> 1.6.0-rc.0"},
{:dart_sass, "~> 0.1", runtime: Mix.env() == :dev}
]
end
- Configure DartSass to use
assets/css/app.scssas the input file andpriv/static/assets/app.cssas the output location.
config :dart_sass,
version: "1.36.0",
default: [
args: ~w(css/app.scss ../priv/static/assets/app.css),
cd: Path.expand("../assets", __DIR__)
]
- Enable watch mode in development. In
config/dev.exsunder the Endpoint config, add this to the watchers section under esbuild.
sass: {
DartSass,
:install_and_run,
[:default, ~w(--embed-source-map --source-map-urls=absolute --watch)]
}
- In your
mix.exsfile, add an alias for deployments.
"assets.deploy": [
"esbuild default --minify",
"sass default --no-source-map --style=compressed",
"phx.digest"
]
- Rename your
assets/css/app.cssfile toassets/css/app.scss. I also renamed my phoenix.css to phoenix.scss to get the import working.
Congratulations, you should now have working sass compiling in your project!