Plugin API
Modern.js's Runtime Plugins allow you to extend and modify the behavior of your application during its React code execution. With Runtime Plugins, you can easily perform initialization tasks, implement React Higher-Order Component (HOC) wrapping, and more.
Runtime plugins need to be configured via the plugins field in src/modern.runtime.ts.
Plugin Structure
A typical Runtime Plugin looks like this:
name: A unique identifier for the plugin.setup: A function that receives anapiobject, which provides all available Runtime plugin APIs.
API Overview
The Runtime Plugin API is primarily divided into the following categories:
- Information Retrieval: Getting runtime configuration and hook functions.
- Lifecycle Hooks: Executing custom logic at different stages of the application's rendering process.
Information Retrieval
api.getRuntimeConfig
Gets the runtime configuration defined by the user in the modern.runtime.ts file.
- Usage:
This method returns a copy of the user's configuration. Modifying the returned value will not affect the original configuration.
api.getHooks
Gets the hook functions that can be triggered manually.
- Type:
- Usage:
Lifecycle Hooks
api.onBeforeRender
Executes before the application renders (including both server-side rendering and client-side rendering). You can use this hook to perform data prefetching, modify the rendering context, etc.
-
Type:
RuntimeContextcontains contextual information about the current request, such as the request object, response object, etc. -
Usage:
- This hook executes before every render, so avoid performing long-running operations.
- You can modify the
contextobject in this hook, and the modifiedcontextwill be passed to subsequent rendering processes.
api.wrapRoot
Allows you to wrap the application's root component with a custom React component. This is commonly used to add global Providers, layout components, etc.
-
Type:
-
Usage:
:::warning
-
It is crucial to pass the
propsto the originalAppcomponent, otherwise, the application may not function correctly. -
The component returned by
wrapRootis recreated on every render, so avoid defining complex logic or state within it.
:::
Advanced Usage
Combining Hooks
You can combine multiple hooks to implement more complex functionality. For example, you can use onBeforeRender to fetch data and then use wrapRoot to pass the data to the entire application via Context: