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 ¶
- func ApplyPathAlias(pathAlias map[string]string, path string) string
- func NewPlugin(optsFunc ...OptionFunc) api.Plugin
- func ParseTsconfigPathAlias(buildOptions *api.BuildOptions) (map[string]string, error)
- func ResolveScssPath(content string, scssFilePath string, pathAlias map[string]string) string
- func ResolveVueStylePath(content string, vueFilePath string, pathAlias map[string]string) string
- type HtmlProcessorOptions
- type IndexHtmlOptions
- type IndexHtmlProcessor
- type OnDisposeProcessor
- type OnEndProcessor
- type OnSassLoadProcessor
- type OnStartProcessor
- type OnVueLoadProcessor
- type OnVueResolveProcessor
- type OptionFunc
- func WithIndexHtmlOptions(indexHtmlOptions IndexHtmlOptions) OptionFunc
- func WithJsExecutor(jsExecutor *jsexecutor.JsExecutor) OptionFunc
- func WithLogger(logger *slog.Logger) OptionFunc
- func WithName(name string) OptionFunc
- func WithOnDisposeProcessor(processor OnDisposeProcessor) OptionFunc
- func WithOnEndProcessor(processor OnEndProcessor) OptionFunc
- func WithOnSassLoadProcessor(processor OnSassLoadProcessor) OptionFunc
- func WithOnStartProcessor(processor OnStartProcessor) OptionFunc
- func WithOnVueLoadProcessor(processor OnVueLoadProcessor) OptionFunc
- func WithOnVueResolveProcessor(processor OnVueResolveProcessor) OptionFunc
- func WithStylePreprocessorOptions(stylePreprocessorOptions map[string]any) OptionFunc
- func WithTemplateCompilerOptions(templateCompilerOptions map[string]any) OptionFunc
- type Options
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ApplyPathAlias ¶ added in v0.1.7
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
ResolveScssPath applies path alias and relative path resolution for @import/@use/@forward/url in SCSS 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