@modern-js/main-doc 2.67.4 → 2.67.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/docs/en/configure/app/plugins.mdx +13 -33
  2. package/docs/en/configure/app/runtime/master-app.mdx +1 -5
  3. package/docs/en/configure/app/runtime/plugins.mdx +58 -0
  4. package/docs/en/configure/app/usage.mdx +1 -1
  5. package/docs/en/guides/advanced-features/_meta.json +1 -0
  6. package/docs/en/guides/advanced-features/bff.mdx +1 -1
  7. package/docs/en/guides/advanced-features/compatibility.mdx +1 -1
  8. package/docs/en/guides/advanced-features/custom-server.mdx +218 -0
  9. package/docs/en/guides/advanced-features/page-performance/inline-assets.mdx +2 -0
  10. package/docs/en/guides/advanced-features/page-performance/optimize-bundle.mdx +1 -1
  11. package/docs/en/guides/advanced-features/web-server.mdx +174 -1
  12. package/docs/en/guides/basic-features/data/data-fetch.mdx +2 -1
  13. package/docs/en/guides/basic-features/html.mdx +3 -3
  14. package/docs/en/guides/basic-features/render/ssr.mdx +2 -2
  15. package/docs/en/guides/concept/entries.mdx +1 -1
  16. package/docs/en/plugin/cli-plugins/api.mdx +6 -0
  17. package/docs/en/plugin/runtime-plugins/api.mdx +37 -12
  18. package/docs/en/tutorials/first-app/c05-loader.mdx +1 -1
  19. package/docs/zh/configure/app/plugins.mdx +3 -24
  20. package/docs/zh/configure/app/runtime/master-app.mdx +1 -5
  21. package/docs/zh/configure/app/runtime/plugins.mdx +58 -0
  22. package/docs/zh/configure/app/usage.mdx +1 -1
  23. package/docs/zh/guides/advanced-features/_meta.json +1 -0
  24. package/docs/zh/guides/advanced-features/custom-server.mdx +216 -0
  25. package/docs/zh/guides/advanced-features/web-server.mdx +174 -1
  26. package/docs/zh/plugin/cli-plugins/api.mdx +6 -0
  27. package/docs/zh/plugin/runtime-plugins/api.mdx +37 -12
  28. package/package.json +2 -2
  29. package/src/i18n/index.ts +1 -1
@@ -2,6 +2,12 @@
2
2
 
3
3
  This document details the API for Modern.js CLI plugins. CLI plugins allow you to extend and customize the functionality of Modern.js projects during the build and development process.
4
4
 
5
+ :::info
6
+
7
+ CLI plugins need to be configured via the [`plugins`](/configure/app/plugins) field in `modern.config.ts`.
8
+
9
+ :::
10
+
5
11
  ## Plugin Basic Structure
6
12
 
7
13
  A typical CLI plugin structure is as follows:
@@ -2,6 +2,12 @@
2
2
 
3
3
  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.
4
4
 
5
+ :::info
6
+
7
+ Runtime plugins need to be configured via the [`plugins`](/configure/app/runtime/plugins) field in `src/modern.runtime.ts`.
8
+
9
+ :::
10
+
5
11
  ## Plugin Structure
6
12
 
7
13
  A typical Runtime Plugin looks like this:
@@ -150,16 +156,35 @@ Allows you to wrap the application's root component with a custom React componen
150
156
  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:
151
157
 
152
158
  ```ts
153
- api.onBeforeRender(async (context) => {
154
- const data = await fetchData(context.req);
155
- context.data = data;
156
- });
157
-
158
- api.wrapRoot((App) => {
159
- return (props) => (
160
- <DataContext.Provider value={props.data}>
161
- <App {...props} />
162
- </DataContext.Provider>
163
- );
164
- });
159
+ import { RuntimePluginFuture, RuntimeReactContext } from '@modern-js/runtime';
160
+ import { useContext, createContext } from 'react';
161
+
162
+ export const ThemeContext = createContext<{ theme: string } | null>(null);
163
+
164
+ export const themePlugin = (): RuntimePluginFuture => {
165
+ return {
166
+ name: 'theme-plugin',
167
+ setup: api => {
168
+ api.onBeforeRender(async context => {
169
+ const userPreference = await fetch('/api/user/theme-settings').then(
170
+ res => res.json(),
171
+ );
172
+ context.data = {
173
+ theme: userPreference.theme,
174
+ };
175
+ });
176
+
177
+ api.wrapRoot(App => {
178
+ return props => {
179
+ const context = useContext(RuntimeReactContext);
180
+ return (
181
+ <ThemeContext.Provider value={context.data}>
182
+ <App {...props} />
183
+ </ThemeContext.Provider>
184
+ );
185
+ };
186
+ });
187
+ },
188
+ };
189
+ };
165
190
  ```
@@ -7,7 +7,7 @@ In the previous chapter, we learned how to add client route.
7
7
 
8
8
  In this chapter, we will learn how to add **Loader** to the routing component.
9
9
 
10
- By far, we have provided data to components through hardcoding. If you want to get data from the remote, you usually use `useEffect` to do it. But when SSR is enabled, `useEffect` will not be executed at the server level, so this SSR can only render a very limited UI.
10
+ So far, we have provided data to components through hardcoding. If you want to get data from the remote, you usually use `useEffect` to do it. But when SSR is enabled, `useEffect` will not be executed at the server level, so this SSR can only render a very limited UI.
11
11
 
12
12
  Modern.js provides the ability of Data Loader to support homogeneous data acquisition in components to maximize the value of SSR.
13
13
 
@@ -1,39 +1,18 @@
1
- ---
2
- sidebar_position: 9
3
- ---
4
-
5
1
  # plugins
6
2
 
7
3
  - **类型:** `CliPlugin[]`
8
4
  - **默认值:** `[]`
9
5
 
10
- 用于配置自定义的 Modern.js 框架插件。
11
-
12
- 自定义插件的编写方式请参考 [如何编写插件](/plugin/plugin-system)。
6
+ 用于配置自定义的 Modern.js 框架 CLI 插件。自定义 CLI 插件的编写方式请参考 [如何编写 CLI 插件](/plugin/introduction.html#cli-插件)。
13
7
 
14
8
  ## 注意事项
15
9
 
16
- 该选项**用于配置框架插件**,如果你需要配置其他类型的插件,请选择对应的配置方式:
10
+ 该选项**用于配置框架 CLI 插件**,如果你需要配置其他类型的插件,请选择对应的配置方式:
17
11
 
18
12
  - 配置 Rsbuild 插件,请使用 [builderPlugins](/configure/app/builder-plugins) 配置项。
19
13
  - 配置 Rspack 或 webpack 插件,请使用 [tools.bundlerChain](/configure/app/tools/bundler-chain) 配置项。
20
14
  - 配置 Babel 插件,请使用 [tools.babel](/configure/app/tools/babel) 配置项。
21
-
22
- ## 插件类型
23
-
24
- Modern.js 中内置了三种不同的框架插件:
25
-
26
- - `CLI 插件`,适用于本地开发、编译构建阶段,可以在命令行和编译阶段扩展各种能力。
27
- - `Server 插件`,适用于服务端。
28
- - `Runtime 插件`,适用于前端运行时。
29
-
30
- 目前 Modern.js 开放了自定义 CLI 插件的能力,Server 插件和 Runtime 插件会在后续开放。
31
-
32
- ## 插件执行顺序
33
-
34
- 默认情况下,自定义插件会按照 `plugins` 数组的顺序依次执行,Modern.js 内置插件的执行时机早于自定义插件。
35
-
36
- 当插件内部使用了控制顺序的相关字段,比如 `pre`、`post` 时,会基于声明的字段对执行顺序进行调整,详见 [插件结构](/plugin/plugin-system)。
15
+ - 配置框架 Runtime 插件,请使用 [runtime 配置文件 plugins](/configure/app/runtime/plugins) 配置项。
37
16
 
38
17
  ## 示例
39
18
 
@@ -1,8 +1,4 @@
1
- ---
2
- title: masterApp
3
- ---
4
-
5
- # runtime.masterApp
1
+ # masterApp
6
2
 
7
3
  - **类型:** `Object`
8
4
 
@@ -0,0 +1,58 @@
1
+ # plugins
2
+
3
+ - **类型:** `RuntimePlugin[]`
4
+ - **默认值:** `[]`
5
+
6
+ 用于配置自定义的 Modern.js Runtime 插件。自定义 Runtime 插件的编写方式请参考 [如何编写 Runtime 插件](/plugin/introduction.html#runtime-插件)。
7
+
8
+ :::info
9
+
10
+ Runtime 插件需要在 `src/modern.runtime.ts` 文件中的 plugins 中进行配置。
11
+
12
+ :::
13
+
14
+ ## 示例
15
+
16
+ 下面是 Runtime 插件的使用示例。
17
+
18
+ ### 使用 npm 上的插件
19
+
20
+ 使用 npm 上的插件,需要通过包管理器安装插件,并通过 import 引入。
21
+
22
+ ```ts title="src/modern.runtime.ts"
23
+ import { defineRuntimeConfig } from '@modern-js/runtime';
24
+ import { myPlugin } from 'my-plugin';
25
+
26
+ export default defineRuntimeConfig({
27
+ plugins: [myPlugin()],
28
+ });
29
+ ```
30
+
31
+ ### 使用本地插件
32
+
33
+ 使用本地代码仓库中的插件,直接通过相对路径 import 引入即可。
34
+
35
+ ```ts title="src/modern.runtime.ts"
36
+ import { defineRuntimeConfig } from '@modern-js/runtime';
37
+ import { myPlugin } from './config/plugin/myPlugin';
38
+
39
+ export default defineRuntimeConfig({
40
+ plugins: [myPlugin()],
41
+ });
42
+ ```
43
+
44
+ ### 插件配置项
45
+
46
+ 如果插件提供了一些自定义的配置项,可以通过插件函数的参数传入配置。
47
+
48
+ ```ts title="src/modern.runtime.ts"
49
+ import { defineRuntimeConfig } from '@modern-js/runtime';
50
+ import { myPlugin } from './config/plugin/myPlugin';
51
+
52
+ export default defineRuntimeConfig({
53
+ plugins: [myPlugin({
54
+ foo: 1,
55
+ bar: 2,
56
+ })],
57
+ });
58
+ ```
@@ -13,7 +13,7 @@ Modern.js 不支持同时在 `package.json` 中和 `modern.config.ts` 中配置
13
13
 
14
14
  **运行时配置**可以在 `src/modern.runtime.(ts|js|mjs)` 文件中配置。
15
15
 
16
- **服务端运行时配置**可以在根路径下的 `modern.server-runtime.config.(ts|js|mjs)` 中进行配置。
16
+ **服务端运行时配置**可以在 `server/modern.server.(ts|js|mjs)` 中进行配置。
17
17
 
18
18
  ## 编译时配置
19
19
 
@@ -23,5 +23,6 @@
23
23
  "label": "server-monitor",
24
24
  "collapsed": true
25
25
  },
26
+ "custom-server",
26
27
  "web-server"
27
28
  ]
@@ -0,0 +1,216 @@
1
+ ---
2
+ sidebar_position: 16
3
+ ---
4
+
5
+ # 自定义 Server
6
+
7
+ Modern.js 将大部分项目需要的服务端能力都进行了封装,通常项目无需进行服务端开发。但在有些开发场景下,例如用户鉴权、请求预处理、添加页面渲染骨架等,项目仍需要对服务端进行定制。
8
+
9
+ ## 自定义 Server 能力
10
+
11
+ 项目目录下创建 `server/modern.server.ts` 文件,可以在这个文件中添加如下配置来扩展 Server:
12
+ - **中间件(Middleware)**
13
+ - **渲染中间件(RenderMiddleware)**
14
+ - **服务端插件(Plugin)**
15
+
16
+
17
+ 其中 **Plugin** 中可以定义 **Middleware** 与 **RenderMiddleware**。 中间件加载流程如下图所示:
18
+
19
+ <img
20
+ src="https://lf3-static.bytednsdoc.com/obj/eden-cn/10eh7nuhpenuhog/server-md-wf.png"
21
+ style={{ width: '100%', maxWidth: '540px' }}
22
+ />
23
+
24
+ ### 基本配置
25
+
26
+ ```ts title="server/modern.server.ts"
27
+ import { defineServerConfig } from '@modern-js/server-runtime';
28
+
29
+ export default defineServerConfig({
30
+ middlewares: [], // 中间件
31
+ renderMiddlewares: [], // 渲染中间件
32
+ plugins: [], // 插件
33
+ });
34
+ ```
35
+
36
+
37
+ ### 类型定义
38
+
39
+ `defineServerConfig` 类型定义如下:
40
+
41
+ ```ts
42
+ import type { MiddlewareHandler } from 'hono';
43
+
44
+ type MiddlewareObj = {
45
+ name: string;
46
+ path?: string;
47
+ method?: 'options' | 'get' | 'post' | 'put' | 'delete' | 'patch' | 'all';
48
+ handler: MiddlewareHandler | MiddlewareHandler[];
49
+ };
50
+ type ServerConfig = {
51
+ middlewares?: MiddlewareObj[];
52
+ renderMiddlewares?: MiddlewareObj[];
53
+ plugins?: (ServerPlugin | ServerPluginLegacy)[];
54
+ }
55
+ ```
56
+
57
+
58
+ ### Middleware
59
+
60
+ Middleware 支持在 Modern.js 服务的**请求处理**与**页面路由**的流程前后,执行自定义逻辑。
61
+ 即自定义逻辑既要处理接口路由,也要作用于页面路由,那么 Middleware 是不二选择。如果仅需要处理 BFF 接口路由,可以通过配置 `path` 为 BFF 的 `prefix` 来实现。
62
+
63
+ :::note
64
+ BFF 场景只有[运行时框架](/guides/advanced-features/bff/frameworks.html)为 Hono 时,BFF 路由才会经过 Middleware。
65
+ :::
66
+
67
+ #### 使用姿势
68
+
69
+ ```ts title="server/modern.server.ts"
70
+ import { defineServerConfig, type MiddlewareHandler } from '@modern-js/server-runtime';
71
+ import { getMonitors } from '@modern-js/runtime';
72
+
73
+ export const handler: MiddlewareHandler = async (c, next) => {
74
+ const monitors = getMonitors();
75
+ const start = Date.now();
76
+
77
+ await next();
78
+
79
+ const end = Date.now();
80
+ // 上报耗时
81
+ monitors.timing('request_timing', end - start);
82
+ };
83
+
84
+ export default defineServerConfig({
85
+ middlewares: [
86
+ {
87
+ name: 'request-timing',
88
+ handler,
89
+ },
90
+ ],
91
+ });
92
+ ```
93
+
94
+ :::warning
95
+ 必须执行 `next` 函数才会执行后续的 Middleware。
96
+ :::
97
+
98
+
99
+ ### RenderMiddleware
100
+
101
+ 如果只需要处理页面渲染的前后执行逻辑,modern.js 也提供了渲染中间件。
102
+
103
+ #### 使用姿势
104
+
105
+ ```ts title="server/modern.server.ts"
106
+ import { defineServerConfig, type MiddlewareHandler } from '@modern-js/server-runtime';
107
+
108
+ // 注入 render 性能指标
109
+ const renderTiming: MiddlewareHandler = async (c, next) => {
110
+ const start = Date.now();
111
+
112
+ await next();
113
+
114
+ const end = Date.now();
115
+ c.res.headers.set('server-timing', `render; dur=${end - start}`);
116
+ };
117
+
118
+ // 修改响应体
119
+ const modifyResBody: MiddlewareHandler = async (c, next) => {
120
+ await next();
121
+
122
+ const { res } = c;
123
+ const text = await res.text();
124
+ const newText = text.replace('<body>', '<body> <h3>bytedance</h3>');
125
+
126
+ c.res = c.body(newText, {
127
+ status: res.status,
128
+ headers: res.headers,
129
+ });
130
+ };
131
+
132
+ export default defineServerConfig({
133
+ renderMiddlewares: [
134
+ {
135
+ name: 'render-timing',
136
+ handler: renderTiming,
137
+ },
138
+ {
139
+ name: 'modify-res-body',
140
+ handler: modifyResBody,
141
+ },
142
+ ],
143
+ });
144
+ ```
145
+
146
+
147
+ ### Plugin
148
+
149
+ Modern.js 支持在自定义插件中为 Server 添加上述 Middleware 及 RenderMiddleware。
150
+
151
+ #### 使用姿势
152
+
153
+
154
+ ```ts title="server/plugins/server.ts"
155
+ import type { ServerPluginLegacy } from '@modern-js/server-runtime';
156
+
157
+ export default (): ServerPluginLegacy => ({
158
+ name: 'serverPlugin',
159
+ setup(api) {
160
+ return {
161
+ prepare(serverConfig) {
162
+ const { middlewares, renderMiddlewares } = api.useAppContext();
163
+
164
+ // 注入服务端数据,供页面 dataLoader 消费
165
+ middlewares?.push({
166
+ name: 'server-plugin-middleware',
167
+ handler: async (c, next) => {
168
+ c.set('message', 'hi modern.js');
169
+ await next();
170
+ // ...
171
+ },
172
+ });
173
+
174
+ // 重定向
175
+ renderMiddlewares?.push({
176
+ name: 'server-plugin-render-middleware',
177
+ handler: async (c, next) => {
178
+ const user = getUser(c.req);
179
+ if (!user) {
180
+ return c.redirect('/login');
181
+ }
182
+
183
+ await next();
184
+ },
185
+ });
186
+ return serverConfig;
187
+ },
188
+ };
189
+ },
190
+ });
191
+ ```
192
+
193
+
194
+ ```ts title="server/modern.server.ts"
195
+ import { defineServerConfig } from '@modern-js/server-runtime';
196
+ import serverPlugin from './plugins/serverPlugin';
197
+
198
+ export default defineServerConfig({
199
+ plugins: [serverPlugin()],
200
+ });
201
+ ```
202
+
203
+
204
+ ```ts title="src/routes/page.data.ts"
205
+ import { useHonoContext } from '@modern-js/server-runtime';
206
+ import { defer } from '@modern-js/runtime/router';
207
+
208
+ export default () => {
209
+ const ctx = useHonoContext();
210
+ // 消费服务端注入的数据
211
+ const message = ctx.get('message');
212
+
213
+ // ...
214
+ };
215
+
216
+ ```
@@ -2,7 +2,11 @@
2
2
  sidebar_position: 16
3
3
  ---
4
4
 
5
- # 自定义 Web Server
5
+ # 自定义 Web Server(不推荐)
6
+
7
+ :::warning
8
+ 自定义 Web Server 兼容但不再推荐使用,扩展 Server 能力请移步 [自定义 Server](/guides/advanced-features/custom-server.html),迁移指南参考 [迁移至新版自定义 Server](/guides/advanced-features/web-server.html#%E8%BF%81%E7%A7%BB%E8%87%B3%E6%96%B0%E7%89%88%E8%87%AA%E5%AE%9A%E4%B9%89-server)。
9
+ :::
6
10
 
7
11
  Modern.js 将大部分项目需要的服务端能力都进行了封装,通常项目无需进行服务端开发。但在有些开发场景下,例如用户鉴权、请求预处理、添加页面渲染骨架等,项目仍需要对服务端进行定制。
8
12
 
@@ -96,3 +100,172 @@ export const afterRender: AfterRenderHook = (ctx, next) => {
96
100
  :::info
97
101
  详细 API 和更多用法可以查看 [Hook](/apis/app/runtime/web-server/hook)。
98
102
  :::
103
+
104
+
105
+ ## 迁移至新版自定义 Server
106
+
107
+ ### 迁移背景
108
+
109
+ Modern.js Server 在不断演进,为了提供更强大的功能,我们对中间件和 Server 插件的定义和使用方式进行了优化。
110
+ 虽然旧版自定义 Web Server 写法仍被兼容,但我们强烈建议您按照本指南进行迁移,以充分利用新版的优势。
111
+
112
+ ### 迁移步骤
113
+
114
+ 1. 升级 Modern.js 版本至 x.67.5 及以上。
115
+ 2. 按照新版定义方式,在 `server/modern.server.ts` 中配置中间件或插件。
116
+ 3. 将 `server/index.ts` 自定义逻辑迁移到中间件或插件中,并参考 `Context` 和 `Next` 差异,更新您的代码。
117
+
118
+ ### Context 差异
119
+
120
+ 新版中间件 handler 类型为 Hono 的 `MiddlewareHandler`,即 `Context` 类型为 `Hono Context`。对比旧版自定义 Web Server 中 `Context` 差异如下:
121
+
122
+ #### UnstableMiddleware
123
+
124
+
125
+ ```ts
126
+ type Body = ReadableStream | ArrayBuffer | string | null;
127
+
128
+ type UnstableMiddlewareContext<
129
+ V extends Record<string, unknown> = Record<string, unknown>,
130
+ > = {
131
+ request: Request;
132
+ response: Response;
133
+ get: Get<V>;
134
+ set: Set<V>;
135
+ // 当前匹配到的路由信息
136
+ route: string;
137
+ header: (name: string, value: string, options?: { append?: boolean }) => void;
138
+ status: (code: number) => void;
139
+ redirect: (location: string, status?: number) => Response;
140
+ body: (data: Body, init?: ResponseInit) => Response;
141
+ html: (
142
+ data: string | Promise<string>,
143
+ init?: ResponseInit,
144
+ ) => Response | Promise<Response>;
145
+ };
146
+ ```
147
+
148
+ UnstableMiddleware `Context` 和 Hono `Context` 的具体差异:
149
+
150
+ | UnstableMiddleware | Hono | 说明 |
151
+ | :----------------------- | :---------------------------- | :------------------------------------------------------------------------ |
152
+ | `c.request` | `c.req.raw` | 参考 [HonoRequest raw](https://hono.dev/docs/api/request#raw) 文档 |
153
+ | `c.response` | `c.res` | 参考 [Hono Context res](https://hono.dev/docs/api/context#res) 文档 |
154
+ | `c.route` | `c.get('route')` | 获取应用上下文信息 |
155
+ | `loaderContext.get` | `honoContext.get` | 通过 `c.set` 注入数据后 dataLoader 中消费:旧版通过 `loaderContext.get` 获取,新版参考 [Plugin](/guides/advanced-features/custom-server.html#使用姿势-2) 示例 |
156
+
157
+ #### Middleware
158
+
159
+ ```ts
160
+ type MiddlewareContext = {
161
+ response: {
162
+ set: (key: string, value: string) => void;
163
+ status: (code: number) => void;
164
+ getStatus: () => number;
165
+ cookies: {
166
+ set: (key: string, value: string, options?: any) => void;
167
+ clear: () => void;
168
+ };
169
+ raw: (
170
+ body: string,
171
+ { status, headers }: { status: number; headers: Record<string, any> },
172
+ ) => void;
173
+ locals: Record<string, any>;
174
+ };
175
+ request: {
176
+ url: string;
177
+ host: string;
178
+ pathname: string;
179
+ query: Record<string, any>;
180
+ cookie: string;
181
+ cookies: {
182
+ get: (key: string) => string;
183
+ };
184
+ headers: IncomingHttpHeaders;
185
+ };
186
+ source: {
187
+ req: IncomingMessage;
188
+ res: ServerResponse;
189
+ };
190
+ };
191
+
192
+ ```
193
+
194
+ Middleware `Context` 和 Hono `Context` 的具体差异:
195
+
196
+ | UnstableMiddleware | Hono | 说明 |
197
+ | :----------------------- | :---------------------------- | :--------------------------------------------------------------------------- |
198
+ | `c.request.cookie` | `c.req.cookie()` | 参考 [Hono Cookie Helper](https://hono.dev/docs/helpers/cookie) 文档 |
199
+ | `c.request.pathname` | `c.req.path` | 参考 [HonoRequest path](https://hono.dev/docs/api/request#path) 文档 |
200
+ | `c.request.url` | - | Hono `c.req.url` 为完整请求路径,自行通过 url 计算 |
201
+ | `c.request.host` | `c.req.header('Host')` | 通过 header 获取 host |
202
+ | `c.request.query` | `c.req.query()` | 参考 [HonoRequest query](https://hono.dev/docs/api/request#query) 文档 |
203
+ | `c.request.headers` | `c.req.header()` | 参考 [HonoRequest header](https://hono.dev/docs/api/request#header) 文档 |
204
+ | `c.response.set` | `c.res.headers.set` | 例:`c.res.headers.set('custom-header', '1')` |
205
+ | `c.response.status` | `c.status` | 例:`c.status(201)` |
206
+ | `c.response.cookies` | `c.header` | 例:`c.header('Set-Cookie', 'user_id=123')` |
207
+ | `c.response.raw` | `c.res` | 参考 [Hono Context res](https://hono.dev/docs/api/context#res) 文档 |
208
+
209
+
210
+ #### Hook
211
+
212
+ ```ts
213
+ type HookContext = {
214
+ response: {
215
+ set: (key: string, value: string) => void;
216
+ status: (code: number) => void;
217
+ getStatus: () => number;
218
+ cookies: {
219
+ set: (key: string, value: string, options?: any) => void;
220
+ clear: () => void;
221
+ };
222
+ raw: (
223
+ body: string,
224
+ { status, headers }: { status: number; headers: Record<string, any> },
225
+ ) => void;
226
+ };
227
+ request: {
228
+ url: string;
229
+ host: string;
230
+ pathname: string;
231
+ query: Record<string, any>;
232
+ cookie: string;
233
+ cookies: {
234
+ get: (key: string) => string;
235
+ };
236
+ headers: IncomingHttpHeaders;
237
+ };
238
+ };
239
+
240
+ type AfterMatchContext = HookContext & {
241
+ router: {
242
+ redirect: (url: string, status: number) => void;
243
+ rewrite: (entry: string) => void;
244
+ };
245
+ };
246
+
247
+ type AfterRenderContext = {
248
+ template: {
249
+ get: () => string;
250
+ set: (html: string) => void;
251
+ prependHead: (fragment: string) => void;
252
+ appendHead: (fragment: string) => void;
253
+ prependBody: (fragment: string) => void;
254
+ appendBody: (fragment: string) => void;
255
+ };
256
+ };
257
+ ```
258
+
259
+ Hook Context 大部分和 Middleware Context 一致,因此我们要额外关注不同 Hook 多余的部分。
260
+
261
+ | UnstableMiddleware | Hono | 说明 |
262
+ | :----------------------- | :---------------------------- | :----------------------------- |
263
+ | `router.redirect` | `c.redirect` | 参考 [Hono Context redirect](https://hono.dev/docs/api/context#redirect) 文档 |
264
+ | `router.rewrite` | - | 暂时没有提供对应的能力 |
265
+ | template API | `c.res` | 参考 [Hono Context res](https://hono.dev/docs/api/context#res) 文档 |
266
+
267
+
268
+ ### Next API 差异
269
+
270
+ 在 Middleware 和 Hook 中,即使不执行 `next`,渲染函数也会执行。
271
+ 在新的设计中,必须执行 `next` 函数才会执行后续的 Middleware。
@@ -2,6 +2,12 @@
2
2
 
3
3
  本文档详细介绍了 Modern.js CLI 插件的 API。CLI 插件允许您在 Modern.js 项目的构建和开发过程中扩展和定制功能。
4
4
 
5
+ :::info
6
+
7
+ CLI 插件需要通过 `modern.config.ts` 中的 [`plugins`](/configure/app/plugins) 字段配置。
8
+
9
+ :::
10
+
5
11
  ## 插件基础结构
6
12
 
7
13
  一个典型的 CLI 插件结构如下: