DEV Community

Christian Sedlmair
Christian Sedlmair

Posted on Edited on

Setup Svelte as Custom Element on Vite

Overview

Why Svelte?

In every app, we have at least one feature that is special and requires complex front-end logic. This is where Svelte gives us and our customers so much pleasure.

Compared to React, which clearly has a larger ecosystem, Svelte is leaner, faster, better integrated, and in my opinion, simply the better technology. To understand the idea of Svelte in comparison to React, please take a look at this entertaining video from Rich Harris, the founder of Svelte, starting at minute 4:13 rethinking reactivity.

Combined with solid system testing (we use Playwright), this is a powerful and reliable framework.

Setup Svelte

For make work svelte fluently we built the gem svelte-on-rails with the related node-package. Please follow the instructions there.

But, first we must make svelte running:

Installation

npm i svelte@latest @sveltejs/vite-plugin-svelte@latest
Enter fullscreen mode Exit fullscreen mode

vite.config.ts

  import { defineConfig } from 'vite'
  import RubyPlugin from 'vite-plugin-ruby'
+ import { svelte } from '@sveltejs/vite-plugin-svelte';

  export default defineConfig({
    plugins: [
      RubyPlugin(),
+     svelte({})
    ]
  })
Enter fullscreen mode Exit fullscreen mode

package.json

{
  ...
  "type": "module" // => otherwise @sveltejs/vite-plugin-svelte would break
}
Enter fullscreen mode Exit fullscreen mode

Restart server.

example component frontend/javascript/HelloWorld.svelte

<h1>Hello World from Svelte</h1>
Enter fullscreen mode Exit fullscreen mode

add on application.js:

import HelloWorld from '../javascript/HelloWorld.svelte'
import { mount } from 'svelte';
const tag = document.getElementById('svelte-hello-world')
mount(HelloWorld, { target: tag })
Enter fullscreen mode Exit fullscreen mode

And you should see your component on the browser.

Overview

Top comments (1)

Collapse
 
patricknelson profile image
Patrick Nelson • Edited

Also check out svelte-retag which is a fork of Chris' svelte-tag and supports nesting as well as slots.