skip to Main Content

I’m trying to use Svelte 5 and SvelteKit inside PHP.

I don’t understand how to use the Imperative component API (https://svelte.dev/docs/svelte/imperative-component-api). Where do I put the following code? Do I put it in src/routes/main.js?

import { mount } from 'svelte';
import App from './App.svelte';

const app = mount(App, {
    target: document.querySelector('#app'),
    props: { some: 'property' }
});

If I use vite build -w to build the project, what is the path of the built JavaScript to put inside the PHP?

<body>
  <h1>
    <?php echo "Hello, $user"; ?>
  </h1>

  <div id="app">
  </div>

  <script src="/path/build/what-is-the-name-of-the-js-file-for-here.js"></script>
</body>

What do I set src/routes/+layout.js to? My assumption is that I should first try making an SPA (https://svelte.dev/docs/kit/single-page-apps) with the following for src/routes/+layout.js:

export const ssr = false;

I made a file with the JavaScript from the Imperative component API, but I don’t see it in build/.

2

Answers


  1. SvelteKit and the static adapter are not really compatible with custom backends that serve their own generated HTML. The output of a SvelteKit application is HTML, JS & CSS, so without the HTML part, the main entry point is missing.

    You could potentially write your own adapter that outputs PHP which then can be processed by the backend and served. Alternatively you could create a component library, compile that down to JS/CSS via a separate build process and just link those files (you will lose pretty much all of the SvelteKit features like routing, though).

    Login or Signup to reply.
  2. Let me help you set up Svelte 5 to work with PHP. I’ll walk you through the necessary steps and file structure.

    // vite.config.js
    import { defineConfig } from 'vite';
    import { svelte } from '@sveltejs/vite-plugin-svelte';
    
    export default defineConfig({
      plugins: [svelte()],
      build: {
        // Build to a directory your PHP can access
        outDir: 'public/build',
        // Generate a manifest for asset fingerprinting
        manifest: true,
        rollupOptions: {
          // Specify your entry point
          input: 'src/main.js',
          output: {
            // Use a predictable name for the main bundle
            entryFileNames: 'app.js',
            // Put all assets in the build directory
            assetFileNames: 'assets/[name][extname]',
            // Put all chunks in a chunks directory
            chunkFileNames: 'chunks/[name].js',
          }
        }
      }
    });
    
    // src/main.js
    import { mount } from 'svelte';
    import App from './App.svelte';
    
    // Wait for DOM to be ready
    document.addEventListener('DOMContentLoaded', () => {
      const app = mount(App, {
        target: document.querySelector('#app'),
        props: { 
          // Your initial props here
          some: 'property'
        }
      });
    });
    
    // src/routes/+layout.js
    export const ssr = false;
    export const prerender = false;
    
    // src/App.svelte
    <script>
      export let some;
    </script>
    
    <div>
      <h1>Svelte App</h1>
      <p>Prop value: {some}</p>
    </div>
    
    

    With this setup, your PHP file should look like this:

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>Svelte + PHP</title>
    </head>
    <body>
      <h1>
        <?php echo "Hello, $user"; ?>
      </h1>
    
      <div id="app"></div>
    
      <script type="module" src="/build/app.js"></script>
    </body>
    </html>
    

    Here’s how to put it all together:

    1. Create your project structure:
    your-project/
    ├── public/
    │   └── build/       # Built files will go here
    ├── src/
    │   ├── routes/
    │   │   └── +layout.js
    │   ├── App.svelte
    │   └── main.js
    ├── package.json
    └── vite.config.js
    
    1. Install dependencies:
    npm install -D vite @sveltejs/vite-plugin-svelte svelte
    
    1. Build and watch for changes:
    vite build --watch
    

    The built files will be in public/build/, and the main JavaScript file will be app.js as configured in the Vite config.

    Key points:

    • The imperative component API code goes in src/main.js
    • The built JavaScript will be at /build/app.js (based on the Vite config)
    • Make sure your PHP server is configured to serve the static files from the public directory
    • The ssr = false setting in +layout.js ensures client-side only rendering
    • We wait for DOMContentLoaded to ensure the #app element exists before mounting
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search