Skip to content

Rendering HTML from Svelte SSR #352

Closed

Description

@jimafisk

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:

Activity

  1. matthewmueller commented on Jan 12, 2023

    @matthewmueller
    Contributor

    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.

  2. locked and limited conversation to collaborators on Jan 12, 2023
  3. converted this issue into a discussion #353 on Jan 12, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions