createdbypete

createdbypete

Alpine.js V3 support for LiveView

Edit: Before copying and pasting anything into your project, it seems like Webpack v5 is needed to build Alpine v3. See posts below.

While trying out the recent V3 release of Alpine.js (:partying_face: Thanks/Congrats Caleb Porzio) in a LiveView project I noticed dropdown menus would be visible on page load.

Commenting out liveSocket.connect() and the Alpine stuff worked again so it pointed to an issue with when LiveView takes over.

TL;DR Besides the new install instructions and upgrade guide it looks like the onBeforeElUpdated code used we all will have used for V2 needs to be changed to the following:

// Before… (Alpine V2)
onBeforeElUpdated(from, to) {
  if (from.__x) { window.Alpine.clone(from.__x, to) }
}

// After… (Alpine V3)
onBeforeElUpdated(from, to) {
  if (from._x_dataStack) { window.Alpine.clone(from, to) }
}

This change has been extracted from the Livewire repo and appears to get things working again after LiveView connects but I haven’t run any extensive tests beyond my dropdown menus working again

PR for the changes need to Support alpine V3 on Livewire for the curious.

Hope this helps someone else out.

Most Liked

happysalada

happysalada

One thing I’ve found out is that you can’t have alpine state as part of the <body> tag. Since liveview acts on the first child of the body, if you had

<body
   x-data="..."
>
   ...

you will have to add another div like

<body>
   <div
      x-data="..."
    >
     ...
   </div>

The previous was working with alpine v2, but with v3 you have to add the div.
Hope it helps someone.

cmo

cmo

can you share your webpack.config.js? I get the following error when upgrading to V3. It doesn’t like the ? in the function name.

ERROR in ./node_modules/alpinejs/dist/module.esm.js 3032:32
Module parse failed: Unexpected token (3032:32)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|     return clone2;
|   };
>   let hide = () => el._x_undoIf?.() || delete el._x_undoIf;
|   effect3(() => evaluate2((value) => {
|     value ? show() : hide();
 @ ./js/app.js 24:0-30 86:16-22 87:0-6
 @ multi ./js/app.js
dblack

dblack

I was seeing the same issue @cmo. I just updated the rest of my node packages (including webpack to v5) and it’s come good. I’m not sure which of the deps needed updating, but my updated package.json looks like this:

{
  "repository": {},
  "description": " ",
  "license": "MIT",
  "engines": {
    "node": ">= 14.16.1"
  },
  "scripts": {
    "deploy": "NODE_ENV=production webpack --mode=production",
    "dev": "webpack --mode=development",
    "watch": "NODE_ENV=development webpack --mode=development --watch"
  },
  "dependencies": {
    "@tailwindcss/forms": "^0.3.3",
    "alpinejs": "^3.0.6",
    "autoprefixer": "^10.2.6",
    "phoenix": "file:../deps/phoenix",
    "phoenix_html": "file:../deps/phoenix_html",
    "phoenix_live_view": "file:../deps/phoenix_live_view",
    "postcss": "^8.3.4",
    "tailwindcss": "^2.1.4",
    "topbar": "^1.0.1"
  },
  "devDependencies": {
    "@babel/core": "^7.14.0",
    "@babel/preset-env": "^7.14.0",
    "babel-loader": "^8.2.2",
    "copy-webpack-plugin": "^8.1.1",
    "css-loader": "^5.2.0",
    "css-minimizer-webpack-plugin": "^1.3.0",
    "glob": "^7.1.7",
    "mini-css-extract-plugin": "^1.5.0",
    "postcss-loader": "^4.3.0",
    "sass": "^1.32.8",
    "sass-loader": "^11.0.1",
    "webpack": "5.36.0",
    "webpack-cli": "^4.6.0"
  }
}

and webpack.config.js:

const path = require('path');
const glob = require('glob');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = (env, options) => {
  const devMode = options.mode !== 'production';

  return {
    entry: {
      'app': glob.sync('./vendor/**/*.js').concat(['./js/app.js'])
    },
    output: {
      path: path.resolve(__dirname, '../priv/static/js'),
      filename: '[name].js',
      publicPath: '/js/'
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          use: {
            loader: 'babel-loader'
          }
        },
        {
          test: /\.[s]?css$/,
          use: [
            MiniCssExtractPlugin.loader,
            'css-loader',
            'postcss-loader',
          ],
        },
        {
          test: /\.svg$/i,
          type: 'asset/inline'
        },
        {
          test: /\.(png|jpg|jpeg|gif)$/i,
          type: 'asset/resource',
        },
        {
          test: /\.(woff|woff2|eot|ttf|otf)$/i,
          type: 'asset/resource',
        },
      ]
    },
    plugins: [
      new MiniCssExtractPlugin({ filename: '../css/app.css' }),
      new CopyWebpackPlugin({
        patterns: [
          { from: 'static/', to: '../' }
        ]
      })
    ],
    mode: options.mode || 'production',
    optimization: {
      minimizer: [
        '...',
        new CssMinimizerPlugin()
      ]
    },
    target: 'node14.16',
    devtool: devMode ? 'source-map' : undefined
  }
};

All of which i borrowed from Use Webpack v5.x for asset bundling by acconrad · Pull Request #4310 · phoenixframework/phoenix · GitHub

Where Next?

Popular in Questions Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

Other popular topics Top

Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 53690 245
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a &gt; b) do {:ok, "a"} end if (a &lt; b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39297 209
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New

We're in Beta

About us Mission Statement