zoedsoupe

zoedsoupe

My Phoenix app does not open a a connection with liveSocket.
Only modifications I made was to add AlpineJS and TailwindCSS and added PWA configs, adding manifest.json and servicerWorker.js n /priv/static

I followed this tutorial for Alpine and Tailwind: Underjord | Getting started with PETAL

And this for PWA: https://truehenrique.com/pwa-com-elixir-e-phoenix-em-5-minutos

Here’s my complete app.js:

// We need to import the CSS so that webpack will load it.
// The MiniCssExtractPlugin is used to separate it out into
// its own CSS file.
import "../css/app.scss";

import Alpine from "alpinejs";

import "./check-cnpj.js";
import "./init-alpine.js";
import "./charts-lines.js";
import "./charts-bars.js";
import "./charts-pie.js";
import "./focus-trap.js";

// webpack automatically bundles all modules in your
// entry points. Those entry points can be configured
// in "webpack.config.js".
//
// Import deps with the dep name or local files with a relative path, for example:
//
//     import {Socket} from "phoenix"
//     import socket from "./socket"
//
import "phoenix_html";
import { Socket } from "phoenix";
import NProgress from "nprogress";
import { LiveSocket } from "phoenix_live_view";

const csrfToken = document
  .querySelector("meta[name='csrf-token']")
  .getAttribute("content");

// Config AlpineJS
const liveSocket = new LiveSocket("/live", Socket, {
  params: { _csrf_token: csrfToken },
  dom: {
    onBeforeElUpdated(from, to) {
      if (from.__x) {
        Alpine.clone(from.__x, to);
      }
    },
  },
});

// Show progress bar on live navigation and form submits
window.addEventListener("phx:page-loading-start", (info) => NProgress.start());
window.addEventListener("phx:page-loading-stop", (info) => NProgress.done());

// connect if there are any LiveViews on the page
liveSocket.connect();

// expose liveSocket on window for web console debug logs and latency simulation:
// >> liveSocket.enableDebug()
// >> liveSocket.enableLatencySim(1000)  // enabled for duration of browser session
// >> liveSocket.disableLatencySim()
window.liveSocket = liveSocket;

I tried to log liveSocket direct from app.js but nothing was printed.

webpack.config.js:

const path = require("path");
const glob = require("glob");
const HardSourceWebpackPlugin = require("hard-source-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const TerserPlugin = require("terser-webpack-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");

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

  return {
    optimization: {
      minimizer: [
        new TerserPlugin({
          cache: true,
          parallel: true,
          sourceMap: devMode,
        }),
        new OptimizeCSSAssetsPlugin({}),
      ],
    },
    entry: {
      app: glob.sync("./vendor/**/*.js").concat(["./js/app.js"]),
    },
    output: {
      filename: "[name].js",
      path: path.resolve(__dirname, "../priv/static/js"),
      publicPath: "/js/",
      libraryTarget: "this",
    },
    devtool: devMode ? "eval-cheap-module-source-map" : undefined,
    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          use: {
            loader: "babel-loader",
          },
        },
        {
          test: /\.[s]?css$/,
          use: [
            MiniCssExtractPlugin.loader,
            "css-loader",
            "postcss-loader",
            "sass-loader",
          ],
        },
      ],
    },
    plugins: [
      new MiniCssExtractPlugin({ filename: "../css/app.css" }),
      new CopyWebpackPlugin([{ from: "static/", to: "../" }]),
    ].concat(devMode ? [new HardSourceWebpackPlugin()] : []),
  };
};

This makes to any live route to perform common HTTP requests, so when I try to submit a form which is under a live view, I get the No route found for POST /xxx/xxx

I also tried to remove all deps: phoenix deps and node_modules.

I have a strange Charts.js error on every page:

Uncaught TypeError: Cannot read property 'length' of null
    at Object.acquireContext (Chart.js?30ef:7756)
    at Chart.construct (Chart.js?30ef:9324)
    at new Chart (Chart.js?30ef:9311)
    at eval (charts-lines.js?5024:73)
    at Module../js/charts-lines.js (app.js:132)
    at __webpack_require__ (app.js:20)
    at eval (app.js?7473:1)
    at Module../js/app.js (app.js:108)
    at __webpack_require__ (app.js:20)
    at Object.0 (app.js:1775)

But I don’t think that it’s that what causing the problem. Maybe a silly mistake of mine that I can’t find?

Trying to access manually the liveSocket which is assigned to the window object, I get undefined :confused:

Showing Posts 1 to 4

sfusato

sfusato

It’s possible you have an error higher on the chain as the console error points. If the Webpack bundling wasn’t successful it won’t get to your console log statement.

I would investigate this first:

at eval (charts-lines.js?5024:73)
at Module../js/charts-lines.js (app.js:132)

Comment out those chart imports in app.js and see if you can single out what causes the error that way.

zoedsoupe

zoedsoupe OP

But if it doesn’t bundle correctly, won’t be any other error logged out?

Indeed… Was chart.j. Why? I didn’t understand, but removing all custom charts solved the problem.

sfusato

sfusato

As far as I know it stops at the first encountered error.

zoedsoupe

zoedsoupe OP

So this was not the problem… Webpack bundled successfully once I have access to other objects inserted into window as data of init-alpine.js

— All posts loaded —

Where Next? Top

Trending in Questions Top

Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
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
matt-savvy
Anyone here using Honeybadger? My Honeybadger account is being overwhelmed with noise from some bots. Seeing a lot of Bandit.HTTPError...
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

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
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
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
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & 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