kalkatfyodor

kalkatfyodor

I have been trying to solve this issue with Alpine in Phoenix 1.6 LiveView:

and it now works.

But the problem is that I am loading alpine.js twice.

Once inside the <head></head> in root.html.heex file and the second time importing like:

<script defer src="https://unpkg.com/alpinejs@3.7.0/dist/cdn.min.js"></script>

and the second time in app.js because I have downloaded the file in the script tag and saves as alpine.js inside assets/vendor/alpine.js in the assets/js/app.js file:

// We import the CSS which is extracted to its own file by esbuild.
// Remove this line if you add a your own CSS build pipeline (e.g postcss).
import "../css/main.css";

// Alpine
import Alpine from "../vendor/alpine";
window.Alpine = Alpine;
Alpine.start();

// If you want to use Phoenix channels, run `mix help phx.gen.channel`
// to get started and then uncomment the line below.
// import "./user_socket.js"

or as suggested by the user in the linked post like:


import { LiveSocket } from "phoenix_live_view";
import topbar from "../vendor/topbar";
import Alpine from "../vendor/alpine";

// Alpine
window.Alpine = Alpine;
Alpine.start();

let csrfToken = document
  .querySelector("meta[name='csrf-token']")
  .getAttribute("content");
let liveSocket = new LiveSocket("/live", Socket, {
  params: { _csrf_token: csrfToken },
  dom: {
    onBeforeElUpdated(from, to) {
      if (from._x_dataStack) {
        window.Alpine.clone(from, to);
      }
    },
  },
});

// Show progress bar on live navigation and form submits
topbar.config({

And it works. But it is loaded twice, at least I think it is leaded twice.

The reason why I have dowloaded the file is that I don’t want to use npm in PHX1.6.

If you suggest to remove the script inside the head tags - well then it will stop working.

The same with removing the import from app.js - it will stop working.

Any idea how to solve that?

Do any of you use Alpine js without using npm? How do you setup your app.js and root.html.heex and other files than?

Now, when I think about it, perhaps it has to be like that in LiveView (and loaded twice) because of the first load static html and then only use websocket principle? Any comments on that?

Or perhaps I am importing it wrongly in app.js? And when I import it correctly, I will be able to remove the script import inside head tags in root.html.heex?

Thanks for any help.

Showing Posts 1 to 10

derek-zhou

derek-zhou

Don’t load any javascript off the internet. You will never know if any of the CDN site is compromised, or DNS hijacked. I’d suggest you to use npm. You don’t have to use webpack and can stick to esbuild.

kalkatfyodor

kalkatfyodor OP

So cdn can be hijacked but npm can’t?
:smiley:
No, thank you. Never will I use npm again. I hate it.
If there is no way to use Alpine with Phoenix 1.6 in LiveView then I will abandon it and go for something else or even vanilla JS but I won’t ever use npm.

derek-zhou

derek-zhou

So cdn can be hijacked but npm can’t?

With a CDN your users are downloading every time with no verification. With NPM, you download the package yourself once, and verify the checksum through the tool. Nothing is bullet proof, but which one do you think is safer?

There is a way to use any javascript lib in phoenix liveview; you only need to figure it out. I would assume importing the correct ES module build of Alpine from my app.js, adding the required initialization and hooks, shall do the job.

wmnnd

wmnnd

It’s possible that some resources are loaded twice in your development environment due to the way live reloads are implemented. Try running your application in prod and this behavior will probably go away.

Also, AlpineJS works very well with LiveView :slight_smile:

wmnnd

wmnnd

This isn’t quite true. You can use Subresource Integrity to make sure your users get a verified version of a given resource from a CDN.
It works by adding an SHA384 hash to the tag that includes the resource.

This is what it would look like for the most recent version of Alpine.

<script src="https://unpkg.com/alpinejs@3.7.0/dist/cdn.min.js" integrity="sha384-RdtRRt1iDhfyBdfZIXH83/BU+0bhkpr746r/OHT0eRgZB0W7gD8bDfabHV42kyyA" crossorigin="anonymous"></script>

You can easily generate these hashes here: https://www.srihash.org/

Sebb

Sebb

The authors care about Phoenix. :+1:

derek-zhou

derek-zhou

I don’t use alpine myself, but there were people posting about their setup before, such as:

Sebb

Sebb

Its as easy as

npm i alpinejs

init

window.Alpine = Alpine
...
Alpine.start() // you may want to do this after other things have initialized

and then hook it in the live socket like

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

change config.exs esbuild config to target es2017.

kalkatfyodor

kalkatfyodor OP

I DO NOT WANT TO USE NPM!!!

Is it clear now? Thank you.

I want to download a file from CDN and save it as alpine.js and use it like you suggest:

import topbar from "../vendor/topbar";
import Alpine from "../vendor/alpine";

window.Alpine = Alpine;
Alpine.start();

let csrfToken = document
  .querySelector("meta[name='csrf-token']")
  .getAttribute("content");
let liveSocket = new LiveSocket("/live", Socket, {
  params: { _csrf_token: csrfToken },
  dom: {
    onBeforeElUpdated(from, to) {
      if (from._x_dataStack) {
        window.Alpine.clone(from, to);
      }
    },
  },
});

But it doesn’t work at all unless I add this line in between the head tags in root.html.heex file:

   <script defer src="https://unpkg.com/alpinejs@3.7.0/dist/cdn.min.js"></script>
  </head>

And now it works great. However it’s probably loaded twice.

The insane thing is that if I remove either one of these scripts Alpine is not working on my site. I don’t get it at all.

By the way, in VS Code I am getting this error when I hover over Alpine in window.Alpine:

Sebb

Sebb

the message was for Derek, and you are free to completely ignore it. And maybe take some time off coding. Maybe clean your car or do some knee bends. :wink:

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
ryanwinchester
apply_graft/2 doesn’t rewrite an add_many sub-workflow’s deps on an add step. Grafted jobs cancel with “upstream job was deleted” Version...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews