How to integrate Svelte in other App Stack

I would like to know if it's possible to integrate Svelte for the front app with a different backend stack than the default one, with a python, Ruby on Rails or PHP server for instance?

Is it possible to use it for a multi-pages app, or should it be used only for single page apps?


Solution 1:

Yes, you can render html tags with any backend.

<div id="svelte-app"></div>
<script src="dist/main.js"></script>

This kind of setup is useful if most of the page is server rendered but you'll want to add some interactive components to a page.

// src/main.js
import App from './App.svelte';

new App({
  target: document.getElementById('svelte-app'),
  props: {
    name: 'world',
  },
});

But you'll need something that performs the Svelte compilation step.

You could use Vite for that:

npm install --save-dev vite svelte @sveltejs/vite-plugin-svelte
// vite.config.js
import path from "path";
import { defineConfig } from "vite";
import { svelte } from '@sveltejs/vite-plugin-svelte';

export default defineConfig({
  plugins: [svelte()],
  build: {
    lib: {
      formats: ["es"],
      fileName: (format)=>`main.js`,
      entry: path.resolve(__dirname, "src/main.js"),
    },
  },
});

Running npx vite build --watch will generate the dist/main.js and recompile on code changes.

Alternatively use rollup-plugin-svelte or svelte-loader if you are already using a bundler.

Solution 2:

There is no difference in integrating Svelte with different backends than there would be with any other frontend technology.

For multipage apps, I recommend using SvelteKit. In this case, there is a special fetch HTTP hook that helps integrations on the server-side rendering and it is recommended all backend APIs are exposed as REST/JSON to have the best support for the fetch SSR handling.

Read my blog post about how I integrated Svelte with Python backend. You can find the actual frontend source code here.