DEV Community

Cover image for Update LiveView for Alpine.js 101
Alessandro Di Maria
Alessandro Di Maria

Posted on • Edited on

6 2

Update LiveView for Alpine.js 101

Today I tried to upgrade Alpine.js V2 to the newly released version 3 in one of my phoenix applications. As with major versions, the new alpine version introduces some breaking changes.

First, you need now to explicitly start alpine with Alpine.start().

import Alpine from "alpinejs";
window.Alpine = Alpine;
Alpine.start();
Enter fullscreen mode Exit fullscreen mode

Second, and this took me some time to figure out, as it is not documented on the changes page, you need to adapt how alpine integrates with LiveView. Before alpine elements had a property __x, that now changed so that you filter now for elements with the _x_dataStack property.

let liveSocket = new LiveSocket("/live", Socket, {
  ...,
  dom: {
    onBeforeElUpdated(from, to){
      if(from._x_dataStack){ 
        window.Alpine.clone(from, to); 
      }
    }
  },
})
Enter fullscreen mode Exit fullscreen mode

That's it! I hope this works for you as well and saves you some time.

Top comments (2)

Collapse
 
theazharul profile image

Change es2016 to es2017 in config.exs file

config :esbuild,
  version: "0.12.18",
  default: [
    args: ~w(js/app.js --bundle --target=es2017 --outdir=../priv/static/assets --external:/fonts/* --external:/images/*),
    cd: Path.expand("../assets", __DIR__),
    env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)}
  ]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
grrrisu profile image
Alessandro Di Maria

Yes! Thanks for pointing out. Alpine >= 3.5 needs target es2017

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more