Search code examples
backendsveltesvelte-3

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

  • 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.