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 '@csedl/svelte-on-rails';
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.debug = true
SvelteOnRails.lazyComponents = import.meta.glob([
"/../../app/views/**/*.svelte",
"/**/*.svelte"
],
{eager: false, import: "default"}
)
lazyComponents
- Paths here are relative to vites
sourceCodeDirfolder. - if
.lazyComponentsis not set, default is used:"/**/*.svelte" import.meta.globis 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 { SvelteOnRails, dispatchSvelteStreamEvent, streamDebugLog } from '@csedl/svelte-on-rails/utils'
SvelteOnRails.debug = true
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
})
Notice that the SvelteOnRails object is available here on a second way (within the utils namespace), beside the above mentioned way over the import on root level. This is to avoid double initialization.
We wrapped the consumer part within setTimeout(() => {.... This would work without it too but is recommended for stability.