I’m currently in the thick of a massive update to our Phoenix LiveView course. (It’ll be a free update if you already own it! 😉) And yesterday I discovered a better way to auto-format HEEx templates in VS Code. Indeed, formatting .heex
files and ~H
sigils is fairly straightforward these days.
1. Add the Mix Formatter Plugin
LiveView 0.17.8 and later includes Phoenix.LiveView.HTMLFormatter for formatting HEEx templates.
It’s a mix format
plugin that’s added to the .formatter.exs
file by default when you generate a Phoenix 1.7 app:
[
plugins: [Phoenix.LiveView.HTMLFormatter],
inputs: ["*.{heex,ex,exs}", "{config,lib,test}/**/*.{heex,ex,exs}", "priv/*/seeds.exs"]
# ...
]
For Phoenix 1.6 apps, just add the plugins
option and include the heex
extension in the existing inputs
option.
With that plugin in the mix (sorry), running mix format
from the command line will format all your HEEx templates.
But you want to auto-format on save in VS Code…
2. Install VS Code Extensions
You’ll need to install two VS Code extensions:
-
ElixirLS for Elixir language support. And, most important to the task at hand, v0.11.0 (August 2022) of this extension added support for mix formatter plugins.
-
Phoenix Framework for syntax highlighting of HEEx templates. It also adds the
phoenix-heex
language id.
3. Add VS Code Settings
Once you have those extensions installed, crack open your VS Code settings.json
and add the following:
"files.associations": {
"*.heex": "phoenix-heex",
// ...
},
"[elixir]": {
"editor.formatOnSave": true,
"editor.defaultFormatter": "JakeBecker.elixir-ls"
},
"[phoenix-heex]": {
"editor.formatOnSave": true,
"editor.defaultFormatter": "JakeBecker.elixir-ls"
},
This associates files with the .heex
extension to the phoenix-heex
language. And it configures ElixirLS to run as the default formatter whenever
an Elixir or HEEx template file is saved.
And that’s all there is to it!
Now for some extra goodies…
Emmet
If you’d like to use Emmet for HTML expansions in HEEx templates (.heex
files and ~H
sigils), add the following to your settings.json
:
"emmet.includeLanguages": {
"phoenix-heex": "html",
"elixir": "html",
// ...
},
Tailwind IntelliSense
Using Tailwind? The Tailwind CSS IntelliSense extension has built-in support for HEEx templates. To activate it for both .heex
files and ~H
sigils, just add the following to your settings.json
:
"tailwindCSS.includeLanguages": {
"phoenix-heex": "html",
"elixir": "html",
// ...
},
🔥 Free Phoenix LiveView Course!
Get my free Phoenix LiveView course and start building interactive, real-time features using all the facets of LiveView. This course has everything you need, assembled in the right order, and in one place! 👍