Different behaviour of Alpine.js (crash) when using LiveView component functions or inline code

Also I want to write more notes and thoughts on Alpine and LiveView.
When the two are used together, they’re both trying to control DOM updates. And the code below is almost every tutorial does to integrate Alpine with LiveView:

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

The source of this integration is from the author of Alpine in this issue: Alpine.js stopped working from LiveView Component on state change. · Issue #809 · phoenixframework/phoenix_live_view · GitHub
Alpine was originally created for Laravel LiveWire, a framework that is kind of similar to Phoenix LiveView. At the time when the issue was posted, LiveWire was also using morphdom for DOM changes and then use Alpine.clone() inside morphdom lifecycle hooks to integrate with Alpine.

But as the author stated in the issue above:

Something that may actually be a deal-breaker for the integration:

Livewire is simple. When an update happens, the server sends an entire chunk of HTML and uses morphdom to patch the existing DOM.

I’ve seen that LiveView has a much more advanced system where the server only sends the dynamic pieces of HTML that have changed.

It’s possible that you are doing something so advanced that you can’t use the simple morphdom hook as I have.

And indeed, with the current way to integrate Alpine with LiveView, you can encounter some unexpected weird behaviors like yours. And some other related problems can also be found in the forum, like what this post mentioned: Proper AlpineJS Integration with Liveview .

But now, LiveWire doesn’t use morphdom for DOM changes anymore. It is using the Alpine Morph plugin, which has the same functionality as morphdom, but it is Alpine-aware. So LiveWire can have seamless integration with Alpine.

And the Alpine.clone() function is marked as deprecated in the latest version. I’m not sure if there’s plan to completely remove it in future releases.

Also, there used to be an instruction on how to integrate Alpine with LiveView in the JavaScript interoperability section of the LivewView doc. But I don’t know when and why it was removed.