Server-side rendering in Svelte #1759
-
Using plot in Svelte is very easy with the integration described here. |
Beta Was this translation helpful? Give feedback.
Replies: 7 comments 1 reply
-
I’m not enough of an expert with Svelte to know whether there’s a way to write a JavaScript component that generates DOM server-side with Svelte. If someone can point me to some examples, I’d be happy to investigate, but a preliminary read of Svelte’s documentation doesn’t suggest how this might be possible. |
Beta Was this translation helpful? Give feedback.
-
Thanks for the quick reply!
This will prerender the svg, I can see it in the server response. If I try this
I get this error: |
Beta Was this translation helpful? Give feedback.
-
I think what you are referring to might be this: https://svelte.dev/docs#template-syntax-svelte-element |
Beta Was this translation helpful? Give feedback.
-
Thanks for the guidance. I think plot/docs/components/PlotRender.js Lines 4 to 111 in 0a38eb8 |
Beta Was this translation helpful? Give feedback.
-
Ok this seems to get rid of the error and I can see that the result of |
Beta Was this translation helpful? Give feedback.
-
Would something like this work for you? <script lang="ts">
import * as Plot from '@observablehq/plot'
import { onMount } from 'svelte'
import * as d3 from 'd3'
let data = d3.ticks(-2, 2, 200).map(Math.sin);
onMount(() => {
let div = document.querySelector('#myPlot')
if (div) {
let plotGraph = Plot.lineY(data).plot({grid: true})
div.append(plotGraph)
}
})
</script>
<div id='myPlot'></div>
This allows the data to come from the server, and then it plots when the page is mounted. Feedback is appreciated ❤️ |
Beta Was this translation helpful? Give feedback.
-
I was successful in forcing the plot to be generated server-side by creating a import * as Plot from '@observablehq/plot';
import { JSDOM } from 'jsdom';
const { document } = new JSDOM().window;
/** @type {import('./$types').PageServerLoad} */
export async function load() {
const plot = Plot.plot({
marks: [
Plot.rectY(
{ length: 10000 },
Plot.binX({ y: "count" }, { x: Math.random })
)
],
document
}).outerHTML;
return {
plot
};
} Then, pick up the HTML string on <script>
/** @type {import('./$types').PageData} */
export let data;
</script>
{@html data.plot} FYI, I tried placing the rendering code in |
Beta Was this translation helpful? Give feedback.
I was successful in forcing the plot to be generated server-side by creating a
+page.server.js
:Then, pick up the HTML string on
+page.svelte
:FYI, I tried placing the rendering code in
+…