Skip to content

Introduction

@meng-xi/vite-plugin is a toolkit that provides practical plugins for Vite, and also serves as a complete Vite Plugin Development Framework.

Built-in Plugins

Fifteen ready-to-use plugins covering common build scenarios:

PluginDescription
assetManifestAutomatically scan build output and generate asset mapping manifest, supporting Vite/Webpack/custom formats, entry grouping, and runtime injection
autoImportAuto-inject import statements with preset mappings, wildcard ('*'), directory scanning, Vue template auto-import, and TypeScript declaration generation
buildProgressDisplay real-time build progress bar in terminal, supporting bar / spinner / minimal formats
bundleAnalyzerBuild artifact size analysis with JSON/HTML reports, gzip calculation, threshold alerts, and build comparison
compressAssetsCompress build artifacts with gzip / brotli / both, configurable compression level, file filtering, and concurrency, plus compression statistics report
copyFileCopy files or directories to specified locations after build, with incremental copying
envGuardEnvironment variable validation with type checking, range validation, custom rules and runtime guard
faviconManagerManage website favicon links injection into HTML files
generateRouterAuto-generate router configuration and TypeScript type declarations from uni-app's pages.json
generateVersionAuto-generate version numbers with file output and global variable injection
htmlInjectHTML content injection with multiple positions and conditions
imageOptimizerAutomatically optimize images after build, supporting JPEG/PNG/WebP/AVIF/GIF/TIFF/SVG compression and format conversion
loadingManagerGlobal Loading state management with XHR/Fetch request interception, white-screen Loading, custom styles & animations, and lifecycle callbacks
proxyManagerDeclarative dev proxy management with environment switching, rule file loading, request logging, delay simulation, and env variable override
versionUpdateCheckerRuntime version update check with refresh prompt

Plugin Development Framework

Export core components to quickly build custom plugins:

ComponentDescription
BasePluginPlugin base class providing lifecycle management, logging, validation, and safe execution wrappers
createPluginFactoryPlugin factory function that handles options merging, normalization, and instantiation
LoggerSingleton logger manager with plugin-level log control
ValidatorChainable configuration validator supporting required, type, enum, range, and custom validation
PluginWithInstanceVite plugin type with plugin instance reference for external access to internal state
PluginFactoryPlugin factory function type definition
OptionsNormalizerOptions normalizer type, supporting conversion from simplified to full configuration

Common Options

All built-in plugins extend BasePlugin and support these common options:

typescript
interface BasePluginOptions {
	/** Enable plugin, default true */
	enabled?: boolean
	/** Show verbose logs, default true */
	verbose?: boolean
	/** Error handling strategy: throw | log | ignore */
	errorStrategy?: 'throw' | 'log' | 'ignore'
}

Common Utility Modules

Eight utility modules covering common scenarios in plugin development:

concurrency — Concurrency Control Utilities

Provides batch async execution with concurrency limits:

  • runWithConcurrency — Concurrently execute async tasks using worker pool pattern, results match input order

format — Formatting Utilities

Provides date formatting parameters, template variable replacement, date formatting, file size formatting, and compression ratio calculation:

  • getDateFormatParams — Get date formatting parameter object
  • parseTemplate — Replace {{key}} placeholders in template strings
  • parseTemplateWithDelimiter — Replace variable placeholders in template strings with custom delimiters
  • formatDate — Format date strings using {key} placeholders
  • formatFileSize — Format bytes into a human-readable file size string
  • calcRatio — Calculate compression ratio percentage

fs — File System Utilities

Provides file operations, directory scanning, safe writing, change detection, report path resolution, file mapping, and batch deletion:

  • checkSourceExists — Check if source path exists
  • copySourceToTarget — Copy files or directories with incremental copying
  • writeFileContent — Async write file content
  • scanDirectory — Recursively scan directory, collect file info with extension and path filtering
  • writeJsonReport — Write data to a JSON file
  • writeFileSyncSafely — Synchronously write file, automatically creating non-existent directories
  • shouldUpdateFileContent — Check if file content needs updating, reducing unnecessary IO
  • resolveReportPath — Resolve report output path
  • scanAndMapFiles — Scan directory and build file path mapping table for quick lookup
  • deleteFiles — Batch delete file list, ignoring non-existent files

html — HTML Injection Utilities

Provides multiple HTML content injection strategies, security filtering, and attribute value escaping:

  • injectBeforeTag — Inject code before a specified closing tag
  • injectHeadAndBody — Dual-zone HTML injection (head + body)
  • sanitizeContent — Sanitize injected content to prevent XSS attacks
  • escapeHtmlAttr — Escape special characters in HTML attribute values

path — Path Processing Utilities

Provides cross-platform path normalization, extension filtering, path exclusion matching, and compression format detection:

  • normalizePath — Convert backslashes to forward slashes for cross-platform consistency
  • isExtensionIncluded — Check if file extension passes include/exclude filter conditions
  • isPathExcluded — Check if file path matches exclude path list, supporting simple / segment matching modes
  • isPreCompressed — Check if extension is a pre-compressed format (.gz or .br)

script — Script Utilities

Provides script generation functionality:

  • makeCallback — Wrap callback function body string into a safe function expression (with try-catch protection)

ui — Terminal UI Utilities

Provides terminal ANSI escape code handling:

  • ANSI — ANSI escape code toolkit providing text coloring (green/cyan/red/yellow/magenta/gray/bold) and cursor control (reset/clearLine/hideCursor/showCursor)

validation — Configuration Validation Utilities

Provides chainable validator and preset validation functions:

  • Validator — Chainable configuration validator supporting required / string / number / boolean / enum / minValue / maxValue / custom validation rules
  • validateGlobalName — Validate the legality of global variable names
  • validateNoScriptInTemplate — Validate template strings don't contain script tags (XSS prevention)
  • validateCallbackFields — Validate callback fields don't contain script tags

Next Steps

Released under the MIT License.