plentico / plenti

Static Site Generator with Go backend and Svelte frontend
https://plenti.co
Apache License 2.0
1k stars 48 forks source link

Importing plain JS Files from components #324

Closed s00500 closed 4 months ago

s00500 commented 4 months ago

I am trying to create a class in a .js file and import it into one of my components. But that seems to not work... any ideas ? or is this not intended in the context of plenti right now ?

I did take a quick look at the build package but did not go through all the regex 🙈

Otherwise this tool is pretty cool!!!! Love it so far

Code:

Component:

<script>
  import { ReconnectingWebSocket } from "../scripts/reconnecting-ws.js";
  export let title, intro, blog, source, content, allContent;

  const url = "ws://localhost:3";
  const ws = new ReconnectingWebSocket(url, []);

  ws.addEventListener("message", event => {
    console.log("Message from server:", event.data);
  });

  ....

Imported file

export class ReconnectingWebSocket {
    constructor(url, protocols = []) {
        this.url = url;
        this.protocols = protocols;
        this.ws = null;
        this.reconnectInterval = 1000; // Initial backoff interval (1 second)
        this.maxReconnectInterval = 30000; // Maximum backoff interval (30 seconds)
        this.reconnectDecay = 1.5; // Exponential backoff factor
        this.connect();
    }

    connect() {

    ....
s00500 commented 4 months ago

I unfortunatly also just realized that I cant use this.ws = new WebSocket(this.url, this.protocols); at all....

neither window.WebSocket(this.url, this.protocols);

jimafisk commented 4 months ago

@s00500 - I assume you're getting a build error like ReferenceError: ReconnectingWebSocket is not defined, is that correct?

The build process creates both the interactive clientside JS (which has access to browser objects like window) and HTML fallbacks (which don't have access to the browser / runtime JS). If I have something that needs to be run clientside only, I typically wrap it in onMount so it's ignored by the SSR part of the build that creates the HTML.

Can you try putting the clientside logic inside onMount and let me know if that help? For example:

<script>
  import { ReconnectingWebSocket } from "../scripts/reconnecting-ws.js";
  import { onMount } from 'svelte';

  let ws;
  onMount(() => {                             
    ws = new ReconnectingWebSocket("ws://localhost:3", []);
  });
</script>
s00500 commented 4 months ago

Hey @jimafisk, that nailed it! Thanks a lot !!! (would ofc be awesome to have a error that can be traced easier ;-) )

jimafisk commented 4 months ago

Awesome, I'm glad it worked @s00500, thanks for following up!