Skip to content
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

Proof-of-concept for transform plugins #234

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions example/compile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const svelte = require("svelte/compiler");

process.stdin.on("data", (buf) => {
const result = svelte.compile(buf.toString("utf8"), {
generate: "dom",
hydratable: true,
format: "esm",
});
console.log(result.js.code);
});
1 change: 1 addition & 0 deletions example/hello.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<h1>hi world!</h1>
65 changes: 65 additions & 0 deletions example/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package main

import (
"bytes"
"fmt"
"os"
"os/exec"
"path/filepath"

"github.com/evanw/esbuild/internal/fs"
"github.com/evanw/esbuild/pkg/api"
)

func main() {
result := api.Build(api.BuildOptions{
EntryPoints: []string{os.Args[1]},
Format: api.FormatESModule,
Bundle: true,
Loaders: map[string]api.Loader{".svelte": api.LoaderJS},
FS: &SvelteFS{fs.RealFS()},
})
for _, warn := range result.Warnings {
fmt.Println("[WARN] ", warn.Text)
}
for _, err := range result.Errors {
fmt.Println("[ERROR] ", err.Text)
}
for _, file := range result.OutputFiles {
fmt.Println(string(file.Contents))
}
}

// SvelteFS filesystem
//
// The idea here is to wrap the existing filesytem
// in a filesystem that transforms.
type SvelteFS struct {
fs.FS
}

var _ fs.FS = (*SvelteFS)(nil)

// ReadFile is transforms any .svelte file
func (fs *SvelteFS) ReadFile(path string) (string, bool) {
if filepath.Ext(path) == ".svelte" {
code, ok := fs.FS.ReadFile(path)
if !ok {
return "", ok
}
// executes ./demo/compile.js
// could be amortized by running it when initializing SvelteFS
cmd := exec.Command("node", filepath.Join("example", "compile.js"))
var stdout bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = os.Stderr
cmd.Stdin = bytes.NewBufferString(code)
err := cmd.Run()
if err != nil {
return "", false
}
// fmt.Println(string(stdout.String()))
return stdout.String(), true
}
return fs.FS.ReadFile(path)
}
Loading