Works together with the svelte-on-rails gem.
- Please follow the gem instructions.
- Svelte >= 5
- tested with ruby 3.2.2 and rails 7.1
npm i @csedl/svelte-on-rails
Create a file like initializeSvelte.js
and import it into your entrypoint file, like application.js
import { initializeSvelteComponents, cleanupSvelteComponents } from '@csedl/svelte-on-rails';
const components = import.meta.glob('/javascript/**/*.svelte', { eager: true });
const componentsRoot = '/javascript';
// Initialize Svelte components
initializeSvelteComponents(componentsRoot, components, true);
// Event listener for hotwired/turbo (if installed!), on page load
document.addEventListener('turbo:load', () => {
initializeSvelteComponents(componentsRoot, components, true);
});
// Event listener for hotwired/turbo (if installed!), before page cache
document.addEventListener('turbo:before-cache', () => {
cleanupSvelteComponents(true);
});
- The last boolean argument is for debugging logs to the browser console
- I also have inserted very detailed error logs.
The helper from the svelte-on-rails
gem adds attributes like
- class
svelte-on-rails-not-initialized-component
- attribute
data-svelte-component="HelloWorld"
- attribute
data-props={items:['one','two','three']}
to the wrapping element. Then, this lib
- picks up these elements
- picks the props, parses them by
JSON.parse(..)
and provides them to the element as svelte props - If the element is empty, it mountes, otherwise it hydrates the element
- adds the attribute
data-svelte-initialized='true'
- removes the class
svelte-on-rails-not-initialized-component
There is a rails project with testings (based on playwright) where the gem and this package are tested together.
The gem includes its own tests.