Modern.js adopts a highly extensible, plugin-based architecture, where its core functionalities and extended capabilities are implemented through plugins. The plugin system not only ensures the framework's flexibility but also provides developers with powerful customization options. This document focuses on how to write Modern.js plugins, helping you quickly get started with plugin development.
Modern.js adheres to the design philosophy of "everything is a plugin," modularizing the framework's various functional components and assembling and extending them through plugins. This design brings several advantages, including:
Modern.js provides three main plugin types, corresponding to different stages of application development:
CLI Plugins:
modern
command).plugins
field in modern.config.ts
.Runtime Plugins:
plugins
field in src/modern.runtime.ts
.A typical Modern.js plugin consists of the following key parts:
Field Descriptions:
name
string
The plugin names declared in pre
, post
, and required
refer to this name
field.
setup
(api: PluginAPI) => MaybePromise<void>
api
PluginAPI
pre
string[]
pre
will be executed before this plugin.post
string[]
post
will be executed after this plugin.required
string[]
If unregistered plugin names are configured in pre
or post
, these plugin names will be automatically ignored and will not affect the execution of other plugins.
If you need to explicitly declare that the plugins that the current plugin depends on must exist, you need to use the required
field.
usePlugins
Plugin
Plugins declared in usePlugins
are executed before the current plugin by default. To execute them after, use the post
declaration.
registryHooks
Record<string, PluginHook<(...args: any[]) => any>>
The core of the Modern.js plugin system is its Hook model, which defines the communication mechanism between plugins. Modern.js mainly provides two types of Hooks:
async/await
.createAsyncHook
.Example:
createSyncHook
.Example:
plugin-xxx
or @scope/plugin-xxx
).Following these best practices can help you develop high-quality, easy-to-maintain, and easy-to-use Modern.js plugins.