zoedsoupe

zoedsoupe

Phoenix doesn't open liveSocket as it's undefined

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:

Marked As Solved

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.

Last Post!

zoedsoupe

zoedsoupe

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

Where Next?

Popular in Questions Top

JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
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
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

Other popular topics Top

JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
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
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New

We're in Beta

About us Mission Statement