Skip to content

Compile and render string as svelte server-side component #12043

Answered by eltigerchino
korywka asked this question in Q&A
Discussion options

You must be logged in to vote

Dug into it a bit more: compiling the JS code for the Svelte component and writing it to disk works. Then, we dynamically import the module on disk, call render, and get the html and css. Hope this helps!

// src/routes/test/+server.js
import { compile } from 'svelte/compiler';
import fs from 'node:fs';

const __dirname = new URL('.', import.meta.url).pathname;
const filename = __dirname + '/component.js';

export async function GET() {
	const result = compile(
		'<div class="container">Hello world</div><style>div { color: red; }</style>',
		{
			generate: 'ssr'
		}
	);

	fs.writeFileSync(filename, result.js.code);

	const { html, css } = (await import(filename)).default.render();

	return n…

Replies: 1 comment 4 replies

Comment options

You must be logged in to vote
4 replies
@korywka
Comment options

@korywka
Comment options

@eltigerchino
Comment options

Answer selected by korywka
@korywka
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants