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 { mount } from "svelte";
    import App from "./App.svelte";
    
    mount(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"),
        },
      },
    });
    

    Check if your package.json already has "type": "module"

    And run npx vite build --watch to 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.