Woes with SSR and Promises
See original GitHub issueI’m having trouble setting up SSR in a Svelte project that utilizes dynamic imports. I’m bundling the app with Rollup, producing a single JS file with dynamic imports inlined.
Best described with code:
<script>
const params = {};
const go = () => import('./views/PageHome.svelte');
</script>
{#await go()}
Loading...
{:then comp}
<svelte:component this={comp.default} {params} />
{/await}
…rendering this on the server will yield
{ html: '\n\t\tLoading...\n\t', css: { code: '', map: null }, head: '' }
Similarly, getting rid of the {#await ...}
block and just setting the route directly like so…
<script>
const params = {};
let Route;
import('./views/PageHome.svelte').then(comp => Route = comp.default);
</script>
<svelte:component this={Route} {params} />
…will yield:
{ html: '', css: { code: '', map: null }, head: '' }
The above code is compiled into this:
const App = create_ssr_component(($$result, $$props, $$bindings, $$slots) => {
const params = {};
let Route;
Promise.resolve().then(function () { return PageHome$1; }).then(comp => Route = comp.default);
return `${validate_component(((Route) || missing_component), 'svelte:component').$$render($$result, { params: params }, {}, {})}`;
});
The issue of course is the promise here.
It’s pretty common to have an app that uses route based code-splitting. How does one, with Svelte, handle server-side rendering in that case? Extract routing outside of the Svelte app, and just render the specific Svelte page components directly?
Are there any good solutions to combining SSR and code-splitting and if so, should they be documented?
Issue Analytics
- State:
- Created 4 years ago
- Reactions:1
- Comments:7 (3 by maintainers)
I do wonder if there is a way Svelte could be adjusted to render resolved promises immediately instead of waiting a minimum of one tick. It could be a nice cheap performance win.
Not through the promise, but there are ways to work around that. I set up
svelte-loadable
that way. It registers the “loaders” so that there is a state handler that works outside of the promises. A pattern like that might not work in every case, I only mention it as an example of how to get around that problem.