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
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).
Let me help you set up Svelte 5 to work with PHP. I’ll walk you through the necessary steps and file structure.
With this setup, your PHP file should look like this:
Here’s how to put it all together:
The built files will be in
public/build/
, and the main JavaScript file will beapp.js
as configured in the Vite config.Key points:
src/main.js
/build/app.js
(based on the Vite config)public
directoryssr = false
setting in+layout.js
ensures client-side only renderingDOMContentLoaded
to ensure the#app
element exists before mounting