Skip to content

Commit

Permalink
WIP: Gopack during compilation (#255).
Browse files Browse the repository at this point in the history
  • Loading branch information
jimafisk committed Mar 8, 2023
1 parent d52d2e7 commit c4d5473
Show file tree
Hide file tree
Showing 6 changed files with 26 additions and 131 deletions.
12 changes: 0 additions & 12 deletions cmd/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,18 +153,6 @@ func Build() error {
log.Fatal("\nError in DataSource build step", err)
}

// Run Gopack (custom Snowpack alternative) on app for ESM support.
err = build.Gopack(buildPath, buildPath+"/spa/core/main.js")
if err != nil {
log.Fatal("\nError in Gopack build step", err)
}

// Run Gopack manually on dynamic imports
err = build.GopackDynamic(buildPath)
if err != nil {
log.Fatal("\nError in GopackDynamic build step", err)
}

// Run Minification
err = build.Minify(buildPath)
if err != nil {
Expand Down
4 changes: 2 additions & 2 deletions cmd/build/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ func Client(buildPath string, coreFS embed.FS) error {
componentStr = string(componentBytes)
}
destPath := buildPath + "/spa/" + strings.TrimSuffix(path, ".svelte") + ".js"
err = (compileSvelte(ctx, SSRctx, path, componentStr, destPath, stylePath))
err = compileSvelte(ctx, SSRctx, buildPath, path, componentStr, destPath, stylePath)
if err != nil {
fmt.Printf("Could not compile '%s' Svelte component: %s", path, err)
}
Expand Down Expand Up @@ -244,7 +244,7 @@ func compileComponent(err error, layoutPath string, layoutFileInfo os.FileInfo,
}
componentStr := string(component)
// Actually compile component
if err = compileSvelte(ctx, SSRctx, layoutPath, componentStr, destFile, stylePath); err != nil {
if err = compileSvelte(ctx, SSRctx, buildPath, layoutPath, componentStr, destFile, stylePath); err != nil {
return compiledComponentCounter, allLayoutsStr, fmt.Errorf("%w\n", err)
}
// Create entry for layouts.js.
Expand Down
6 changes: 5 additions & 1 deletion cmd/build/compile.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ var (
reCSSCli = regexp.MustCompile(`var(\s)css(\s)=(\s)\{(.*\n){0,}\};`)
)

func compileSvelte(ctx *v8go.Context, SSRctx *v8go.Context, layoutPath string,
func compileSvelte(ctx *v8go.Context, SSRctx *v8go.Context, buildPath string, layoutPath string,
componentStr string, destFile string, stylePath string) error {

// Create any sub directories need for filepath.
Expand All @@ -56,6 +56,10 @@ func compileSvelte(ctx *v8go.Context, SSRctx *v8go.Context, layoutPath string,
return fmt.Errorf("V8go could not execute js.code for %s: %w\n", layoutPath, err)
}
jsBytes := []byte(jsCode.String())
jsBytes, err = Gopack(buildPath, destFile, jsBytes)
if err != nil {
return fmt.Errorf("Could not add ESM support via Gopack: %w", err)
}
err = os.WriteFile(destFile, jsBytes, 0755)
if err != nil {
return fmt.Errorf("Unable to write compiled client file: %w\n", err)
Expand Down
93 changes: 18 additions & 75 deletions cmd/build/gopack.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,11 @@ import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"time"

"github.com/plentico/plenti/readers"
)
Expand Down Expand Up @@ -40,38 +38,10 @@ var (
rePath = regexp.MustCompile(`(?:'|").*(?:'|")`)
)

// Initialize globally to keep track during recursion.
var alreadyConvertedFiles []string

// Gopack ensures ESM support for NPM dependencies.
func Gopack(buildPath, entrypoint string) error {

defer Benchmark(time.Now(), "Running Gopack")

Log("\nRunning gopack to build esm support for npm dependencies")

// Clear web_modules from previous build.
alreadyConvertedFiles = []string{}

// Start at the entry point for the app
err := runPack(buildPath, entrypoint)
if err != nil {
return err
}

return nil
}

func runPack(buildPath, convertPath string) error {
func Gopack(buildPath string, convertPath string, contentBytes []byte) ([]byte, error) {
// Destination path for dependencies
gopackDir := buildPath + "/spa/web_modules"

// Get the actual contents of the file we want to convert
contentBytes, err := ioutil.ReadFile(convertPath)
if err != nil {
return fmt.Errorf("\nCould not read file %s to convert to esm\n%w", convertPath, err)
}

// Created byte array of all dynamic imports in the current file.
dynamicImportPaths := reDynamicImport.FindAll(contentBytes, -1)
for _, dynamicImportPath := range dynamicImportPaths {
Expand Down Expand Up @@ -101,6 +71,8 @@ func runPack(buildPath, convertPath string) error {
var foundPath string
// Initialize the full path of the import.
var fullPathStr string
// Initialize error.
var err error

// Convert .svelte file extensions to .js so the browser can read them.
if filepath.Ext(pathStr) == ".svelte" {
Expand Down Expand Up @@ -180,53 +152,24 @@ func runPack(buildPath, convertPath string) error {
}
}

// Do not convert files that have already been converted to avoid loops.
if !alreadyConverted(fullPathStr, alreadyConvertedFiles) {
// Add the current file to list of already converted files.
alreadyConvertedFiles = append(alreadyConvertedFiles, fullPathStr)
// Use fullPathStr recursively to find its imports.
err = runPack(buildPath, fullPathStr)
if err != nil {
return fmt.Errorf("\nCan't runPack on %s %w", fullPathStr, err)
//if foundPath != "" {
// Remove "public" build dir from path.
replacePath := strings.Replace(foundPath, buildPath, "", 1)
// Wrap path in quotes.
replacePath = "'" + replacePath + "'"
// Convert string path to bytes.
replacePathBytes := []byte(replacePath)
// Actually replace the path to the dependency in the source content.
contentBytes = bytes.ReplaceAll(contentBytes, staticStatement,
rePath.ReplaceAll(staticStatement, rePath.ReplaceAll(pathBytes, replacePathBytes)))
/*
} else {
return contentBytes, fmt.Errorf("\nImport path '%s' not resolvable from file '%s'\n", pathStr, convertPath)
}
}

if foundPath != "" {
// Remove "public" build dir from path.
replacePath := strings.Replace(foundPath, buildPath, "", 1)
// Wrap path in quotes.
replacePath = "'" + replacePath + "'"
// Convert string path to bytes.
replacePathBytes := []byte(replacePath)
// Actually replace the path to the dependency in the source content.
contentBytes = bytes.ReplaceAll(contentBytes, staticStatement,
rePath.ReplaceAll(staticStatement, rePath.ReplaceAll(pathBytes, replacePathBytes)))
} else {
return fmt.Errorf("\nImport path '%s' not resolvable from file '%s'\n", pathStr, convertPath)
}
}
// Overwrite the old file with the new content that contains the updated import path.
err = ioutil.WriteFile(convertPath, contentBytes, 0644)
if err != nil {
return fmt.Errorf("Could not overwite %s with new import: %w\n", convertPath, err)
*/
}
return nil

}
return contentBytes, nil

func alreadyConverted(convertPath string, alreadyConvertedFiles []string) bool {
// Check if there are already files that have been converted
if len(alreadyConvertedFiles) > 0 {
for _, convertedFile := range alreadyConvertedFiles {
// Compare the currently queued file with each already converted file
if convertPath == convertedFile {
// Exit the function to avoid endless loops where files
// reference each other (like main.js and router.svelte)
return true
}
}
}
return false
}

func pathExists(path string) bool {
Expand Down
40 changes: 0 additions & 40 deletions cmd/build/gopack_dynamic.go

This file was deleted.

2 changes: 1 addition & 1 deletion defaults/core/main.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import Router from './router.svelte';
import Router from './router.js';

new Router({
target: document,
Expand Down

0 comments on commit c4d5473

Please sign in to comment.