Plugin Architecture in Practice: A Guide to Five Plugin Types with Code Examples
This article presents a practical methodology for plugin development, broken down into five common plugin types: minimal, tool-based, event-based, configuration-based, and service-based. You will learn a shared three-step skeleton for setting up the loading pipeline, how to use overlay configuration to contribute code incrementally, and the key design principles for each plugin type, including dependency injection, automatic cleanup, schema validation, and stable service contracts. The article also covers how to combine plugin types and a fixed troubleshooting order for isolating loading issues from logic issues. All directory layouts, overlay settings, and startup steps are illustrative and should be adapted to your framework's conventions.
Plugin Architecture in Practice: A Guide to Five Plugin Types with Code Examples
Why Runnable Examples Beat Specification Docs
When learning and adopting a plugin system, developers often run into a conflict. Specification documents are complete and define clear boundaries, but they are expensive to read and tend to leave you at the level of “knowing the concept.” Runnable example code, on the other hand, is scattered, yet it shows within minutes whether the pipeline is wired up correctly.
A more pragmatic approach is to combine the two: use a minimal runnable example to validate the environment, then layer on capabilities step by step until you have a complete mental model of the plugin mechanism.
This article abstracts a general methodology for plugin development and organizes it into five common forms: minimal plugins, tool-based plugins, event-based plugins, configuration-based plugins, and service-based plugins. Together they cover the vast majority of business extension scenarios. They are not mutually exclusive; they can be combined and stacked. The directory layouts, overlay configuration, and startup methods shown here are illustrative, meant to convey the approach. When applying them in practice, adjust to the conventions of your specific framework.
The Common Skeleton: Three Steps to a Working Loading Pipeline
All five forms share the same project structure and startup method. The only difference is what gets registered in the source code. This “unified skeleton, pluggable capabilities” design is key to keeping maintenance costs low in a plugin system.
Step 1: Create a Dedicated Directory
Create a separate plugin workspace under the checkout root. It is recommended to keep the source and the overlay configuration at the same level for easier management and version control:
project-root/ # checkout root (source build already completed)└── scratch-plugin/├── src/│ └── my-plugin.ts # examples for all five forms go here└── overlay.yml # overlay configuration
Isolating experimental plugins from the main project source has obvious benefits: it does not pollute the trunk code, it is easy to delete at any time, and when loading fails, it is easy to locate the problem boundary.
Step 2: Write the Overlay Configuration
The core purpose of an overlay is to “contribute configuration incrementally,” not to change the root path used for module resolution. The configuration must point to the absolute path of the plugin source:
insert:- id: demoname: '/absolute/path/to/project-root/scratch-plugin/src/my-plugin.ts'
One high-frequency pitfall must be emphasized here: the path must be absolute. The overlay only appends configuration entries; module resolution still follows the existing profile directory rules. As a result, relative paths often cause loading failures, and the error messages are not very informative.
Step 3: Start and Observe
Start the web service with the overlay. The expected result is that the UI works normally and the plugin is mounted into the plugin tree. If you do not see the expected logs, check three things first: whether the path is correct, whether the source has been built, and whether the configuration syntax follows the convention. Do not stack on more features before the pipeline is working, or the problem will be amplified.
Form 1: Minimal Plugin — Validate the Environment and Loading Pipeline
A minimal plugin has a single responsibility: prove that “the file is found, the module is loaded, and the lifecycle function is called.” Example code:
import type { Context } from 'some-plugin-runtime-types'export const name = 'hello-plugin'export function apply(ctx: Context) {console.log('[hello-plugin] plugin loaded!')}
Here, name is the plugin’s unique identifier in the plugin tree, used for conflict detection and dependency references. apply is the entry function; it receives the context object and is the mount point for all subsequent capabilities. After startup, the corresponding log is printed to the terminal, which means the pipeline is working. This step looks simple, but it is the most efficient link for troubleshooting, because it completely separates “the environment is not set up” from “the code is wrong.”
Form 2: Tool-Based Plugin — Expose Capabilities to the Model
The goal of a tool-based plugin is to let the model call the capabilities you have wrapped. There are two implementation points. First, declare dependency injection, stating that this plugin needs to write to the tool registry. Second, use the unified tool definition method to describe the name, parameter structure, execution logic, and error return.
export const inject = ['tools']export function apply(ctx: Context) {ctx.tools.defineTool({name: 'query_order_status',description: 'Query the current status by order ID',parameters: { /* parameter structure definition */ },async execute(args) {// call an internal service and return a structured resultreturn { ok: true, data: null }}})}
Several practices should be followed when designing tools: descriptions should be readable by the model, parameter names should be semantic, the return structure should be stable and include an explicit success/failure flag, and exceptions must be caught and converted into readable information rather than throwing stack traces directly at the model. Tool granularity is also worth weighing: too coarse makes it hard for the model to compose calls correctly, while too fine increases the number of call rounds and the probability of errors.
Form 3: Event-Based Plugin — Insert Logic at Framework Timings and Clean Up Automatically
Event-based plugins insert cross-cutting logic at specific framework timings, such as when a request comes in, when a result is returned, or when a session ends. The key is “registration is bound to the lifecycle”: you register a listener through the side-effect management mechanism provided by the context, and when the plugin is unloaded, the unbinding happens automatically, avoiding memory leaks and duplicate triggers.
export function apply(ctx: Context) {ctx.effect(() => {const handler = (payload) => { /* handling logic */ }ctx.on('event:name', handler)return () => ctx.off('event:name', handler)})}
Automatic cleanup is one of the core advantages that distinguish a plugin system from ordinary modules. In scenarios where plugins can be hot-swapped and started or stopped gradually, if cleanup logic relies on manual maintenance by developers, listener accumulation, performance degradation, and inconsistent behavior will inevitably appear over long-running periods. Therefore, it is recommended to: bring all external resources (timers, connections, subscriptions) under unified scope management; keep cleanup functions idempotent; and set timeouts and fallback paths for time-consuming operations.
Form 4: Configuration-Based Plugin — Let Users Adjust Behavior
Configuration-based plugins solve the problem of “one codebase adapting to multiple scenarios.” The approach is to define a configuration type with accompanying schema validation, and let the framework handle parsing and validity checks at load time. Invalid configuration fails at startup instead of producing hard-to-trace exceptions at runtime.
export interface Config {level: 'debug' | 'info' | 'warn'maxRetry: number}export const schema = { /* schema constraints matching Config */ }export function apply(ctx: Context, config: Config) {// decide behavior based on config}
A few rules of thumb for configuration design: defaults must be safe and usable; numeric parameters should have lower and upper bounds; enumerations should be listed explicitly; sensitive information should not be written into the configuration file but injected through the environment; and configuration changes should be observable, so it is recommended to print a summary of the key effective items at load time, making it easier to investigate on site “why the behavior does not match expectations.”
Form 5: Service-Based Plugin — Let Other Plugins Reuse You
A service-based plugin exposes a stable interface, and other plugins obtain an instance through dependency injection. A typical form is to export a service class, register it in apply, and declare the plugins it depends on.
export const inject = ['tools']export class OrderService {constructor(private ctx: Context) {}async get(id: string) { /* return a unified structure */ }}export function apply(ctx: Context) {ctx.provide('orderService', new OrderService(ctx))}
The key to service-oriented design is a stable contract: clear interface semantics, distinguishable error types, and an explicit version compatibility strategy. It is recommended to follow the principle of minimal exposure and publish only the necessary methods; keep internal implementation details encapsulated; and when service initialization fails, provide actionable error information instead of letting dependents discover a null instance at runtime.
Composition and Troubleshooting Tips
The five forms can be freely combined: a plugin can be configuration-based while also providing a service and registering tools. Things to watch when combining them include: controlling the number of plugins and the depth of dependencies to avoid circular dependencies; doing necessary performance observation on high-frequency call paths, and establishing a baseline with general logging services and monitoring/alerting capabilities; and during gradual rollout, first validating the pipeline with a minimal plugin before enabling tool and service capabilities.
A fixed troubleshooting order is more efficient: first confirm the path and build artifacts, then confirm the dependency injection declarations are complete, then check whether configuration validation passes, and only then review the business logic. Handling “loading problems” and “logic problems” in separate layers can significantly shorten the time to locate an issue. Once you master these five forms and the unified skeleton, plugin development shifts from “groping through the docs” to “assembling by pattern,” which is the greatest value of example-driven learning.
