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.
A typical Runtime Plugin looks like this:
name
: A unique identifier for the plugin.setup
: The main logic of the plugin, which receives an api
object as a parameter. This api
object is used to register hooks.The Runtime Plugin API is primarily divided into the following categories:
api.getRuntimeConfig
Gets the runtime configuration defined by the user in the modern.runtime.ts
file.
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.
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:
RuntimeContext
contains contextual information about the current request, such as the request object, response object, etc.
Usage:
context
object in this hook, and the modified context
will 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:
props
to the original App
component, otherwise, the application may not function correctly.wrapRoot
is recreated on every render, so avoid defining complex logic or state within it.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: