Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rendering HTML from Svelte SSR #352

Closed
jimafisk opened this issue Jan 11, 2023 · 1 comment
Closed

Rendering HTML from Svelte SSR #352

jimafisk opened this issue Jan 11, 2023 · 1 comment

Comments

@jimafisk
Copy link

Hi @matthewmueller!

I was exploring how I might leverage your V8 / Svelte compilation in Plenti. Your API is really nicely written 👌

Simple example compiling Svelte files from a "templates" folder to an "output" folder
package main

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"

	v8 "github.com/livebud/bud/package/js/v8"
	"github.com/livebud/bud/package/svelte"
)

func main() {
	vm, _ := v8.Load()
	svelteCompiler, _ := svelte.Load(vm)

	filepath.Walk("templates", func(path string, info os.FileInfo, err error) error {
		if !info.IsDir() && filepath.Ext(path) == ".svelte" {
			fileContents, _ := os.ReadFile(path)
			destPath := "output" + strings.TrimPrefix(path, "templates")
			os.MkdirAll(filepath.Dir(destPath), os.ModePerm)

			DOM, _ := svelteCompiler.DOM(path, fileContents)
			ioutil.WriteFile(strings.TrimSuffix(destPath, ".svelte")+"_DOM.js", []byte(DOM.JS), os.ModePerm)

			SSR, _ := svelteCompiler.SSR(path, fileContents)
			ioutil.WriteFile(strings.TrimSuffix(destPath, ".svelte")+"_SSR.js", []byte(SSR.JS), os.ModePerm)
		}
		return nil
	})
}

My question: Is there a way to run Component.render(props) from your svelte package to generate HTML? Thank you!

Related issues:

@matthewmueller
Copy link
Contributor

matthewmueller commented Jan 12, 2023

Hey @jimafisk 🙂

So those functions are for compiling one Svelte file. I'm guessing in Plenti, you'll want to support imports as well. To do that you'll need to wrap those functions as plugins in ESBuild to get one large blob of bundle JS.

You can find that code here:

func (c *Generator) Compile(fsys fileSystem) ([]byte, error) {

(The transformer contains the Svelte compiler)

Once you have that blob of JS, you can call v8.Eval on it:

result, err := vm.Eval("render.js", string(code)+`; bud.render("`+path+`", `+string(input)+`)`)

That would call Component.render() and return HTML.

@livebud livebud locked and limited conversation to collaborators Jan 12, 2023
@matthewmueller matthewmueller converted this issue into discussion #353 Jan 12, 2023

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants