penguin/AstroJS

Javascript framework for my blog

resolver-go/internal/minifier/css/compiler.go

raw ยท 808 bytes

package css

import (
	"context"
	"fmt"

	"github.com/evanw/esbuild/pkg/api"
	"github.com/tgckpg/resolver-go/internal/compilecache"
)

func NewEsbuildCompiler() *EsbuildCompiler {
	return &EsbuildCompiler{}
}

func (c *EsbuildCompiler) Compile(ctx context.Context, job compilecache.Job) ([]byte, error) {
	payload, ok := job.Payload.(CompilePayload)
	if !ok {
		return nil, fmt.Errorf("esbuild css compiler got invalid payload type %T", job.Payload)
	}

	result := api.Transform(payload.Source, api.TransformOptions{
		Loader:            api.LoaderCSS,
		Sourcefile:        payload.Name,
		MinifyWhitespace:  true,
		MinifyIdentifiers: true,
		MinifySyntax:      true,
	})

	if len(result.Errors) > 0 {
		return nil, fmt.Errorf("css compile failed: %s", result.Errors[0].Text)
	}

	return result.Code, nil
}