vueplugin

package module
v0.1.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 18, 2025 License: Apache-2.0 Imports: 21 Imported by: 0

README

esbuild-plugin-vue-go

English | 简体中文

Test codecov Go Report Card GoDoc

A pure Golang esbuild plugin for resolving and loading Vue3 single-file components (SFC), with no Node.js dependency.

This project is inspired by pipe01/esbuild-plugin-vue3.

Features & Limitations

This project is experimental and currently supports only limited features, Some advanced Vue SFC features or edge cases may not be fully supported.

  1. Supports standard Vue <script> and <script setup> blocks written in JavaScript or TypeScript.
  2. <template> only supports standard Vue template syntax. Other template languages (such as Pug) are not supported.
  3. <style> supports CSS, SCSS, and SASS. @use are not supported in Sass/SCSS, please use @import instead.
  4. Supports generating HTML files and automatic injection of built JS/CSS assets.
    You can use a custom IndexHtmlProcessor to modify the HTML generation logic
  5. Provides plugin hooks for custom processors at various build stages for advanced customization, including:OnStartProcessor/OnVueResolveProcessor/OnVueLoadProcessor/ OnSassLoadProcessor/OnEndProcessor/OnDisposeProcessor/IndexHtmlProcessor

Quick Start

1. Install
go get github.com/buke/esbuild-plugin-vue-go
2. Example Usage
import (
    "fmt"
    vueplugin "github.com/buke/esbuild-plugin-vue-go"
    "github.com/buke/esbuild-plugin-vue-go/engine"
    jsexecutor "github.com/buke/js-executor"
    "github.com/evanw/esbuild/pkg/api"
)

func main() {
    // 1. Create a new JavaScript executor and start it.
    jsExec, _ := jsexecutor.NewExecutor(
        jsexecutor.WithJsEngine(engine.NewVueCompilerFactory()),
    )
    if err := jsExec.Start(); err != nil {
        panic(err)
    }
    defer jsExec.Stop()

    // 2. Create a Vue plugin with the JavaScript executor and additional options.
    vuePlugin := vueplugin.NewPlugin(
        vueplugin.WithJsExecutor(jsExec),
        vueplugin.WithIndexHtmlOptions(vueplugin.IndexHtmlOptions{
            SourceFile:      "example/vue-example/index.html",
            OutFile:         "example/dist/index.html",
            RemoveTagXPaths: []string{"//script[@src='/src/main.ts']"},
        }),
        vueplugin.WithOnEndProcessor(vueplugin.SimpleCopy(map[string]string{
            "example/vue-example/public/favicon.ico": "example/dist/favicon.ico",
        })),
    )

    // 3. Build the Vue application using esbuild with the Vue plugin.
    buildResult := api.Build(api.BuildOptions{
        EntryPoints: []string{"example/vue-example/src/main.ts"},
        PublicPath:  "example/dist/assets",
        Tsconfig:    "example/vue-example/tsconfig.app.json",
        Loader: map[string]api.Loader{
            ".png":  api.LoaderFile,
            ".scss": api.LoaderCSS,
            ".sass": api.LoaderCSS,
            ".svg":  api.LoaderFile,
        },
        Target:            api.ES2020,
        Platform:          api.PlatformBrowser,
        Format:            api.FormatESModule,
        Bundle:            true,
        Outdir:            "example/dist/assets",
        Plugins:           []api.Plugin{vuePlugin},
        Metafile:          true,
        Write:             true,
        EntryNames:        "[dir]/[name]-[hash]",
        Splitting:         true,
        MinifyWhitespace:  true,
        MinifyIdentifiers: true,
        MinifySyntax:      true,
    })

    // 4. Print build result or errors.
    if buildResult.Errors != nil {
        for _, err := range buildResult.Errors {
            fmt.Printf("Build error: %s\n", err.Text)
        }
    } else {
        fmt.Println("Build succeeded!")
    }
}
3. Advanced Usage

You can use custom processors (hooks) to extend or modify the build process at various stages.
For example, you can preprocess Vue or Sass files, customize HTML output, or run custom logic before/after build.

Below is an example of using custom processors:

import (
    vueplugin "github.com/buke/esbuild-plugin-vue-go"
    "github.com/evanw/esbuild/pkg/api"
    "fmt"
)

// Custom processor: print a message before build starts
func myStartProcessor(buildOptions *api.BuildOptions) error {
    fmt.Println("Build is starting!")
    return nil
}

// Custom processor: modify Vue file content before compilation
func myVueLoadProcessor(content string, args api.OnLoadArgs, buildOptions *api.BuildOptions) (string, error) {
    // For example, inject a comment at the top of every Vue file
    return "// Processed by myVueLoadProcessor\n" + content, nil
}

func main() {
    // ... (create jsExec as in previous examples)

    vuePlugin := vueplugin.NewPlugin(
        vueplugin.WithJsExecutor(jsExec),
        vueplugin.WithOnStartProcessor(myStartProcessor),
        vueplugin.WithOnVueLoadProcessor(myVueLoadProcessor),
        // You can add other processors as needed
    )

    result := api.Build(api.BuildOptions{
        // ...esbuild options...
        Plugins: []api.Plugin{vuePlugin},
    })
}

Supported Processors:

  • OnStartProcessor: Run custom logic before the build starts.
  • OnVueResolveProcessor: Customize how Vue files are resolved.
  • OnVueLoadProcessor: Transform or preprocess Vue file content before compilation.
  • OnSassLoadProcessor: Transform or preprocess Sass/SCSS file content before compilation.
  • OnEndProcessor: Run custom logic after the build finishes.
  • OnDisposeProcessor: Cleanup logic after the build is disposed.
  • IndexHtmlProcessor: Customize HTML file processing and asset injection after build.

How It Works

This project uses github.com/buke/js-executor and github.com/buke/quickjs-go to embed a JavaScript engine (QuickJS) and run JavaScript in Go.
It loads the official @vue/compiler-sfc JavaScript code and calls it directly to compile .vue files.
For Sass/SCSS support, it uses the pure JavaScript Dart Sass package (not the native binary), so all Sass/SCSS compilation is also handled inside the embedded JS engine—no Node.js or native binaries required.

Therefore, you can compile Vue files without a Node.js runtime environment.
However, you still need to use npm install (or another package manager) to install the required JavaScript dependencies for your project, so that esbuild can find and build them.

License

Apache-2.0

Documentation

Overview

Example

Example demonstrates how to use the Vue plugin with esbuild. This function shows the typical workflow: create a JS executor, configure the plugin, and run a build.

package main

import (
	"fmt"

	vueplugin "github.com/buke/esbuild-plugin-vue-go"
	qjscompiler "github.com/buke/esbuild-plugin-vue-go/engines/quickjs-go"

	jsexecutor "github.com/buke/js-executor"
	"github.com/evanw/esbuild/pkg/api"
)

func main() {
	// 1. Create a new JavaScript executor and start it.
	jsExec, _ := jsexecutor.NewExecutor(
		jsexecutor.WithJsEngine(qjscompiler.NewVueCompilerFactory()),
	)
	if err := jsExec.Start(); err != nil {
		panic(err)
	}
	defer jsExec.Stop()

	// 2. Create a Vue plugin with the JavaScript executor and additional options.
	vuePlugin := vueplugin.NewPlugin(
		vueplugin.WithJsExecutor(jsExec),
		vueplugin.WithIndexHtmlOptions(vueplugin.IndexHtmlOptions{
			SourceFile:      "example/vue-example/index.html",
			OutFile:         "example/dist/index.html",
			RemoveTagXPaths: []string{"//script[@src='/src/main.ts']"},
		}),
		vueplugin.WithOnEndProcessor(vueplugin.SimpleCopy(map[string]string{
			"example/vue-example/public/favicon.ico": "example/dist/favicon.ico",
		})),
	)

	// 3. Build the Vue application using esbuild with the Vue plugin.
	buildResult := api.Build(api.BuildOptions{
		EntryPoints: []string{"example/vue-example/src/main.ts"},
		PublicPath:  "example/dist/assets",
		Tsconfig:    "example/vue-example/tsconfig.app.json",
		Loader: map[string]api.Loader{
			".png":  api.LoaderFile,
			".scss": api.LoaderCSS,
			".sass": api.LoaderCSS,
			".svg":  api.LoaderFile,
		},
		Target:            api.ES2020,
		Platform:          api.PlatformBrowser,
		Format:            api.FormatESModule,
		Bundle:            true,
		Outdir:            "example/dist/assets",
		Plugins:           []api.Plugin{vuePlugin},
		Metafile:          true,
		Write:             true,
		EntryNames:        "[dir]/[name]-[hash]",
		Splitting:         true,
		MinifyWhitespace:  true,
		MinifyIdentifiers: true,
		MinifySyntax:      true,
	})

	// 4. Print build result or errors.
	if buildResult.Errors != nil {
		for _, err := range buildResult.Errors {
			fmt.Printf("Build error: %s\n", err.Text)
		}
	} else {
		fmt.Println("Build succeeded!")
	}

}
Output:

Build succeeded!

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ApplyPathAlias added in v0.1.7

func ApplyPathAlias(pathAlias map[string]string, path string) string

applyPathAlias applies path alias mapping to the given import path. It supports both exact aliases and wildcard patterns using '*'.

For exact aliases (e.g., "@utils" -> "/src/utils"):

  • The alias must match the entire path
  • Replacement is direct substitution

For wildcard aliases (e.g., "@/*" -> "/src/*"):

  • The '*' captures any remaining path segments
  • The captured content is substituted in the target path

Examples:

  • "@/components/Button" with "@/*" -> "/src/*" becomes "/src/components/Button"
  • "@utils" with "@utils" -> "/src/utils" becomes "/src/utils"

Returns the original path if no alias matches.

func NewPlugin

func NewPlugin(optsFunc ...OptionFunc) api.Plugin

NewPlugin creates a new esbuild plugin for Vue SFC support. It accepts a list of OptionFunc to customize plugin behavior such as: - JavaScript executor configuration - Template compiler options - Style preprocessor options - Custom processor chains for various build phases

The plugin handles Vue Single File Components (.vue), Sass files (.scss/.sass), and HTML files with comprehensive build integration.

Example usage:

plugin := NewPlugin(
  WithJsExecutor(jsExec),
  WithTemplateCompilerOptions(map[string]interface{}{"sourceMap": true}),
)

Panics if jsExecutor is not provided, as it's required for Vue compilation.

func ParseTsconfigPathAlias added in v0.1.7

func ParseTsconfigPathAlias(buildOptions *api.BuildOptions) (map[string]string, error)

parseTsconfigPathAlias parses path aliases from tsconfig for module resolution. It supports both raw tsconfig JSON and file-based tsconfig configurations.

The function handles two scenarios: 1. When TsconfigRaw is provided (inline JSON configuration) 2. When Tsconfig file path is provided (reads from file system)

It extracts compilerOptions.paths from the tsconfig and converts them to absolute paths based on the tsconfig directory location.

Returns a map where keys are alias patterns (e.g., "@/*") and values are absolute file system paths (e.g., "/project/src/*").

func ResolveScssPath added in v0.1.7

func ResolveScssPath(content string, scssFilePath string, pathAlias map[string]string) string

ResolveScssPath applies path alias and relative path resolution for @import/@use/@forward/url in SCSS content. All rewritten paths are POSIX-style relative paths.

func ResolveVueStylePath added in v0.1.7

func ResolveVueStylePath(content string, vueFilePath string, pathAlias map[string]string) string

ResolveVueStylePath applies path alias and relative path resolution for <style> blocks in Vue SFC content. All rewritten paths are POSIX-style relative paths.

Types

type HtmlProcessorOptions

type HtmlProcessorOptions struct {
	ScriptAttrBuilder func(filename string, htmlSourceFile string) []html.Attribute // JS script tag attribute builder
	CssAttrBuilder    func(filename string, htmlSourceFile string) []html.Attribute // CSS link tag attribute builder
}

HtmlProcessorOptions holds builder functions for script and CSS tag attributes. These builders allow customization of how JavaScript and CSS assets are injected into HTML.

type IndexHtmlOptions

type IndexHtmlOptions struct {
	SourceFile          string               // Source HTML file path to process
	OutFile             string               // Output HTML file path after processing
	RemoveTagXPaths     []string             // XPath expressions for removing specific HTML nodes
	IndexHtmlProcessors []IndexHtmlProcessor // Custom processors for HTML transformation
}

IndexHtmlOptions holds configuration options for HTML file processing. Used to configure how HTML files are processed and transformed during the build.

type IndexHtmlProcessor

type IndexHtmlProcessor func(doc *html.Node, result *api.BuildResult, opts *Options, build *api.PluginBuild) error

IndexHtmlProcessor is a function type for processing HTML files after build. Receives the HTML document node, BuildResult, plugin options, and PluginBuild context. Can modify the HTML DOM, inject scripts/styles, or perform other HTML transformations. Returns an error if the processing fails.

func DefaultHtmlProcessor added in v0.1.3

func DefaultHtmlProcessor(htmlProcessorOptions *HtmlProcessorOptions) IndexHtmlProcessor

NewHtmlProcessor returns an IndexHtmlProcessor that injects JS and CSS tags and removes specified nodes. It processes build output files and automatically injects appropriate script and link tags into the HTML head. The processor supports custom attribute builders for fine-grained control over tag generation.

type OnDisposeProcessor

type OnDisposeProcessor func(buildOptions *api.BuildOptions)

OnDisposeProcessor is a function type for cleanup logic after the build is disposed. Receives the BuildOptions as input and should perform resource cleanup, temporary file removal, or connection closure. Note: Dispose processors should not return errors as cleanup should be best-effort.

type OnEndProcessor

type OnEndProcessor func(result *api.BuildResult, buildOptions *api.BuildOptions) error

OnEndProcessor is a function type for processing logic after the build ends. Receives the BuildResult and BuildOptions as input and can perform post-build processing, asset manipulation, file copying, or result analysis. Returns an error if the processing fails.

func SimpleCopy

func SimpleCopy(fileMap map[string]string) OnEndProcessor

SimpleCopy returns an OnEndProcessor that copies files from fileMap after build completion. Each key-value pair in fileMap represents srcFile -> outFile mapping. This is a utility function for common file copying operations in build workflows.

Example usage:

processor := SimpleCopy(map[string]string{
  "src/assets/favicon.ico": "dist/favicon.ico",
  "public/robots.txt": "dist/robots.txt",
})

type OnSassLoadProcessor

type OnSassLoadProcessor func(content string, args api.OnLoadArgs, buildOptions *api.BuildOptions) (string, error)

OnSassLoadProcessor is a function type for custom Sass file loading logic. Receives the file content, OnLoadArgs, and BuildOptions, returns the (possibly transformed) content and error. If content is returned, it will be used instead of reading from the file system. Return empty string to fallback to default file reading behavior.

type OnStartProcessor

type OnStartProcessor func(buildOptions *api.BuildOptions) error

OnStartProcessor is a function type for processing logic before the build starts. Receives the esbuild BuildOptions as input and can perform pre-build initialization, configuration validation, or environment setup. Returns an error if the processing fails, which will abort the build.

type OnVueLoadProcessor

type OnVueLoadProcessor func(content string, args api.OnLoadArgs, buildOptions *api.BuildOptions) (string, error)

OnVueLoadProcessor is a function type for custom Vue file loading logic. Receives the file content, OnLoadArgs, and BuildOptions, returns the (possibly transformed) content and error. This allows for content transformation, preprocessing, or dynamic content injection before Vue compilation.

type OnVueResolveProcessor

type OnVueResolveProcessor func(args *api.OnResolveArgs, buildOptions *api.BuildOptions) (*api.OnResolveResult, error)

OnVueResolveProcessor is a function type for custom Vue file resolution logic. Receives the OnResolveArgs and BuildOptions, returns an optional OnResolveResult and error. If the processor returns a non-nil OnResolveResult, it will be used as the final result. If nil is returned, the default resolution logic will be used.

type OptionFunc

type OptionFunc func(*Options)

OptionFunc is a function type for configuring plugin options using the functional options pattern. Each option function receives the options struct and modifies it to customize plugin behavior.

func WithIndexHtmlOptions

func WithIndexHtmlOptions(indexHtmlOptions IndexHtmlOptions) OptionFunc

WithIndexHtmlOptions sets the HTML processing options. Configures how HTML files are processed, including source/output paths and custom processors.

func WithJsExecutor

func WithJsExecutor(jsExecutor *jsexecutor.JsExecutor) OptionFunc

WithJsExecutor sets the JavaScript executor for Vue compilation. The JS executor is required and handles communication with the Vue compiler running in a JavaScript context. It's used for compiling Vue Single File Components and processing style files.

func WithLogger

func WithLogger(logger *slog.Logger) OptionFunc

WithLogger sets a custom logger for the plugin. The logger is used for debug information, warnings, and error messages throughout the plugin. Defaults to slog.Default() if not specified.

func WithName

func WithName(name string) OptionFunc

WithName sets a custom plugin name for identification in esbuild logs and error messages. Useful when running multiple instances of the plugin with different configurations.

func WithOnDisposeProcessor

func WithOnDisposeProcessor(processor OnDisposeProcessor) OptionFunc

WithOnDisposeProcessor adds an OnDisposeProcessor to the processor chain. Dispose processors are executed during cleanup and should handle resource cleanup, temporary file removal, or connection closure.

func WithOnEndProcessor

func WithOnEndProcessor(processor OnEndProcessor) OptionFunc

WithOnEndProcessor adds an OnEndProcessor to the processor chain. End processors are executed after the build completes and can perform post-processing, file copying, asset manipulation, or build result analysis.

func WithOnSassLoadProcessor

func WithOnSassLoadProcessor(processor OnSassLoadProcessor) OptionFunc

WithOnSassLoadProcessor adds an OnSassLoadProcessor to the processor chain. Sass load processors can provide custom content for Sass files, enabling dynamic imports, content generation, or preprocessing.

func WithOnStartProcessor

func WithOnStartProcessor(processor OnStartProcessor) OptionFunc

WithOnStartProcessor adds an OnStartProcessor to the processor chain. Start processors are executed before the build begins and can perform setup tasks, validation, or environment preparation.

func WithOnVueLoadProcessor

func WithOnVueLoadProcessor(processor OnVueLoadProcessor) OptionFunc

WithOnVueLoadProcessor adds an OnVueLoadProcessor to the processor chain. Load processors can transform Vue file content before compilation, enabling preprocessing, content injection, or dynamic code generation.

func WithOnVueResolveProcessor

func WithOnVueResolveProcessor(processor OnVueResolveProcessor) OptionFunc

WithOnVueResolveProcessor adds an OnVueResolveProcessor to the processor chain. Resolve processors can customize how Vue file imports are resolved, enabling custom path mapping, virtual modules, or dynamic resolution logic.

func WithStylePreprocessorOptions

func WithStylePreprocessorOptions(stylePreprocessorOptions map[string]any) OptionFunc

WithStylePreprocessorOptions sets the style preprocessor options. These options are passed to style preprocessors (Sass, Less, Stylus) and can include: - includePaths: []string - Additional paths for @import resolution - outputStyle: string - CSS output style (expanded, compressed, etc.) - sourceMap: boolean - Generate source maps for styles

func WithTemplateCompilerOptions

func WithTemplateCompilerOptions(templateCompilerOptions map[string]any) OptionFunc

WithTemplateCompilerOptions sets the Vue template compiler options. These options are passed directly to the Vue compiler and can include: - sourceMap: boolean - Generate source maps for templates - compilerOptions: object - Vue compiler specific options - transformAssetUrls: object - Asset URL transformation rules

type Options added in v0.1.2

type Options struct {
	// contains filtered or unexported fields
}

options holds all plugin configuration and processor chains. This is the internal configuration structure used by the plugin to manage all settings, compiler options, and processor chains.

Directories

Path Synopsis
engines

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL