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:
| Plugin | Description |
|---|---|
| assetManifest | Automatically scan build output and generate asset mapping manifest, supporting Vite/Webpack/custom formats, entry grouping, and runtime injection |
| autoImport | Auto-inject import statements with preset mappings, wildcard ('*'), directory scanning, Vue template auto-import, and TypeScript declaration generation |
| buildProgress | Display real-time build progress bar in terminal, supporting bar / spinner / minimal formats |
| bundleAnalyzer | Build artifact size analysis with JSON/HTML reports, gzip calculation, threshold alerts, and build comparison |
| compressAssets | Compress build artifacts with gzip / brotli / both, configurable compression level, file filtering, and concurrency, plus compression statistics report |
| copyFile | Copy files or directories to specified locations after build, with incremental copying |
| envGuard | Environment variable validation with type checking, range validation, custom rules and runtime guard |
| faviconManager | Manage website favicon links injection into HTML files |
| generateRouter | Auto-generate router configuration and TypeScript type declarations from uni-app's pages.json |
| generateVersion | Auto-generate version numbers with file output and global variable injection |
| htmlInject | HTML content injection with multiple positions and conditions |
| imageOptimizer | Automatically optimize images after build, supporting JPEG/PNG/WebP/AVIF/GIF/TIFF/SVG compression and format conversion |
| loadingManager | Global Loading state management with XHR/Fetch request interception, white-screen Loading, custom styles & animations, and lifecycle callbacks |
| proxyManager | Declarative dev proxy management with environment switching, rule file loading, request logging, delay simulation, and env variable override |
| versionUpdateChecker | Runtime version update check with refresh prompt |
Plugin Development Framework
Export core components to quickly build custom plugins:
| Component | Description |
|---|---|
| BasePlugin | Plugin base class providing lifecycle management, logging, validation, and safe execution wrappers |
| createPluginFactory | Plugin factory function that handles options merging, normalization, and instantiation |
| Logger | Singleton logger manager with plugin-level log control |
| Validator | Chainable configuration validator supporting required, type, enum, range, and custom validation |
| PluginWithInstance | Vite plugin type with plugin instance reference for external access to internal state |
| PluginFactory | Plugin factory function type definition |
| OptionsNormalizer | Options normalizer type, supporting conversion from simplified to full configuration |
Common Options
All built-in plugins extend BasePlugin and support these common options:
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 objectparseTemplate— Replace{{key}}placeholders in template stringsparseTemplateWithDelimiter— Replace variable placeholders in template strings with custom delimitersformatDate— Format date strings using{key}placeholdersformatFileSize— Format bytes into a human-readable file size stringcalcRatio— 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 existscopySourceToTarget— Copy files or directories with incremental copyingwriteFileContent— Async write file contentscanDirectory— Recursively scan directory, collect file info with extension and path filteringwriteJsonReport— Write data to a JSON filewriteFileSyncSafely— Synchronously write file, automatically creating non-existent directoriesshouldUpdateFileContent— Check if file content needs updating, reducing unnecessary IOresolveReportPath— Resolve report output pathscanAndMapFiles— Scan directory and build file path mapping table for quick lookupdeleteFiles— 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 taginjectHeadAndBody— Dual-zone HTML injection (head + body)sanitizeContent— Sanitize injected content to prevent XSS attacksescapeHtmlAttr— 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 consistencyisExtensionIncluded— Check if file extension passes include/exclude filter conditionsisPathExcluded— Check if file path matches exclude path list, supporting simple / segment matching modesisPreCompressed— Check if extension is a pre-compressed format (.gzor.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 rulesvalidateGlobalName— Validate the legality of global variable namesvalidateNoScriptInTemplate— Validate template strings don't contain script tags (XSS prevention)validateCallbackFields— Validate callback fields don't contain script tags
Next Steps
- Installation - Quick start
- assetManifest - Asset manifest generation
- autoImport - Auto import
- buildProgress - Build progress display
- bundleAnalyzer - Build artifact size analysis
- compressAssets - Build artifact compression
- copyFile - File copying
- envGuard - Environment variable validation
- faviconManager - Favicon management
- generateRouter - Router generation
- generateVersion - Version management
- htmlInject - HTML content injection
- imageOptimizer - Image optimization
- loadingManager - Global Loading state management
- proxyManager - Dev proxy management
- versionUpdateChecker - Version update detection
- Plugin Factory - Develop custom plugins
- GitHub - View source code and examples
