Plugins
Plugins are self-contained code that add global-level functionality to Vue applications. They are the primary mechanism for distributing reusable functionality to the Vue community.What is a Plugin?
A plugin is either:- An object with an
installmethod - A function that acts as the install function
- Global components
- Global directives
- Global properties or methods
- Global mixins
- Library integrations
Plugin Anatomy
Based onruntime-core/src/apiCreateApp.ts, there are two plugin formats:
Object Plugin
Function Plugin
Installing Plugins
Use theapp.use() method to install plugins:
Plugin Installation Behavior
From the source implementation:- Plugins are only installed once (duplicate installations are ignored)
- Returns the app instance for chaining
- Can be a function or object with
installmethod
Basic Plugin Example
Here’s a simple plugin that adds a global method:Plugin Capabilities
1. Register Global Components
2. Register Global Directives
3. Add Global Properties
4. Provide Injectable Values
5. Add Global Mixins
Real-World Plugin: Router Integration
Here’s a more complete example inspired by Vue Router:Plugin with TypeScript
Create type-safe plugins:Plugin Configuration
Handle plugin options effectively:Plugin Cleanup
Plugins can register cleanup functions:apiCreateApp.ts, the onUnmount hook is available on the app instance:
Best Practices
1. Namespace Global Properties
Prefix global properties to avoid conflicts:2. Use Provide/Inject
Prefer provide/inject over global properties:3. Document Options
Provide clear documentation for plugin options:4. Support Tree-Shaking
Export individual features for better tree-shaking:5. Provide TypeScript Declarations
Include type declarations for TypeScript users:Testing Plugins
Test plugins in isolation:Plugin Examples
Popular Vue plugins to study:- Vue Router: Routing solution
- Pinia: State management
- Vue I18n: Internationalization
- VueUse: Collection of composables
- Vuelidate: Form validation