Configuration of Javascript

For the basic functionality of the javascript part, just run (if not already done by the install generator):

npm i @csedl/svelte-on-rails

and add

import { SvelteOnRails } from '@csedl/svelte-on-rails/setup';
SvelteOnRails.start();

to your entrypoint file.

Then, hydration and building functionality of svelte components on the frontend is set up. 😉👍

Options

you also can add some options:

import {SvelteOnRails} from '@csedl/svelte-on-rails'
SvelteOnRails.start({
    debug: true,
    lazyComponents: import.meta.glob([
            "/../../app/views/**/*.svelte",
            "/**/*.svelte"
        ],
        {eager: false, import: "default"}
    )
})

lazyComponents

  • Paths here are relative to vites sourceCodeDir folder.
  • if .lazyComponents is not set, default is used: "/**/*.svelte"
  • import.meta.glob is a vite feature and the only option at this place.
  • {eager: false, import: "default"} is mandatory.

Stream Functions

For the stream functionality, you can use Modules from the utils namespace:

import { createConsumer } from "@rails/actioncable"
import { dispatchSvelteStreamEvent, streamDebugLog } from '@csedl/svelte-on-rails'

window.addEventListener('load', () => {
    setTimeout(() => {
        const consumer = createConsumer()

        consumer.subscriptions.create("SvelteOnRailsChannel", {
            connected() {
                streamDebugLog("Connected to SvelteOnRailsChannel")
            },
            disconnected() {
                streamDebugLog("Disconnected from SvelteOnRailsChannel")
            },
            received(data) {
                streamDebugLog("Received:", data)
                dispatchSvelteStreamEvent(data)
            }})
    }, 100)  // or 300-500 if 100 not enough
})

We wrapped the consumer part within setTimeout(() => {.... This would work without it too but is recommended for stability.