@modern-js/main-doc 3.11.0 → 3.11.2

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.
@@ -37,3 +37,40 @@ If the value of `supportHtml5History` is `true`, `BrowserRouter` would be used,
37
37
  When SSR is enabled, `supportHtml5History` is not supported.
38
38
 
39
39
  :::
40
+
41
+ ## useTransitions
42
+
43
+ - **Type:** `boolean`
44
+ - **Default:** `undefined`, which follows React Router's default behavior (enabled)
45
+
46
+ Whether to wrap router state updates in [`React.startTransition`](https://react.dev/reference/react/startTransition). The value is passed to React Router's [`<RouterProvider useTransitions>`](https://reactrouter.com/api/data-routers/RouterProvider).
47
+
48
+ When enabled, the page mount after the initial Data Loader finishes and every navigation are rendered concurrently. Benefits:
49
+
50
+ - During navigation, the current page stays on screen until the next page is ready, instead of showing a loading state first.
51
+ - Rendering can yield to the main thread, so the page keeps responding to user input while switching pages.
52
+
53
+ It also introduces two behaviors that differ from synchronous rendering:
54
+
55
+ - A render may be discarded and run again. Component bodies, `useMemo` and `useState` initializers, and class component constructors may run more than once, so code in them that changes external state (such as creating an instance and assigning it to a global variable, registering event listeners, or sending analytics) also runs more than once.
56
+ - There may be a gap between render and commit. External state read during render may have changed by the time it is subscribed to in `useLayoutEffect`, and updates that happen in the gap are lost.
57
+
58
+ If your application contains such code and cannot be refactored yet, set it to `false` to render router state updates synchronously:
59
+
60
+ ```ts title="src/modern.runtime.ts"
61
+ import { defineRuntimeConfig } from '@modern-js/runtime';
62
+
63
+ export default defineRuntimeConfig({
64
+ router: {
65
+ useTransitions: false,
66
+ },
67
+ });
68
+ ```
69
+
70
+ :::tip
71
+
72
+ - This option only affects router state updates. Updates triggered by `startTransition` or `useTransition` in your own code are not affected.
73
+ - See the [React Router documentation](https://reactrouter.com/explanation/react-transitions) for how to make your code transition-safe.
74
+ - `future.v7_startTransition` is deprecated. When `useTransitions` is not set, the value of `future.v7_startTransition` is used.
75
+
76
+ :::
@@ -15,7 +15,7 @@ Choose a release containing MCP Apps support. Run `pnpm dev`. The explicit BFF r
15
15
 
16
16
  ## Build cards
17
17
 
18
- Declare local default-export React components or this project's MF exposes in `mcp-views.json`:
18
+ Declare local default-export React components, this project's MF exposes, or exposes of deployed remotes in `mcp-views.json`:
19
19
 
20
20
  ```json
21
21
  {
@@ -44,6 +44,31 @@ mcpAppsPlugin({
44
44
  });
45
45
  ```
46
46
 
47
+ ### Reference deployed remotes
48
+
49
+ When another project publishes the card as an MF remote, set `remote` to the manifest URL of the remote:
50
+
51
+ ```json
52
+ {
53
+ "remote": "https://ui.example.com/mf-manifest.json",
54
+ "views": {
55
+ "todos": { "expose": "./Todos" },
56
+ "stats": { "expose": "./Stats" }
57
+ },
58
+ "csp": { "resourceDomains": ["https://cdn.example.com"] }
59
+ }
60
+ ```
61
+
62
+ The top-level `remote` is shared by all expose views. A view can set its own `remote` to override it. Component paths still reference local components. Without a top-level or view-level `remote`, exposes refer to this application. With a top-level `remote`, expose views in the same config cannot refer to this application's exposes. To mix both, omit the top-level `remote` and set `remote` only on the views that reference a deployed remote.
63
+
64
+ - The URL must be an absolute HTTP(S) URL whose path ends with `.json`. Entries that are not manifests, such as `remoteEntry.js`, are not supported
65
+ - The remote's name is not needed. The runtime reads it from the manifest
66
+ - The shell reads the remote manifest and loads the expose when the card opens. Republishing the remote needs no rebuild or restart of the MCP server. Exposes are not checked at build time. A missing expose shows a load error in the card
67
+ - This project does not need the MF plugin, but it must install the runtime that `mf.runtime` points to. Set `mf.runtime` as above when the remote uses another MF implementation
68
+ - The manifest origin is added to CSP automatically. Declare other origins serving the remote's scripts and styles, such as a CDN, in `csp.resourceDomains`. The manifest and scripts must allow cross-origin requests
69
+ - The remote must share React as a singleton so it uses the shell's React
70
+ - Adding a card or changing `remote` or `expose` still requires rebuilding the MCP server
71
+
47
72
  Local cards build as separate entries without the framework page runtime. With `source.enableAsyncEntry`, each entry adds a dynamic import boundary so MF shared dependencies can initialize. The MF plugin enables this option automatically. Otherwise cards mount directly without an extra request.
48
73
 
49
74
  {/* prettier-ignore */}
@@ -17,3 +17,5 @@ Based on server-side runtime logic, Modern.js provides the following log events:
17
17
  import InternalLogger from '@site-docs-en/components/internal-logger.mdx';
18
18
 
19
19
  <InternalLogger />
20
+
21
+ To configure the built-in production server logger with `MODERN_SERVER_LOG_LEVEL`, see [Production server logs](../../basic-features/deploy#production-server-logs).
@@ -111,6 +111,12 @@ export const action = async ({ request }: ActionFunctionArgs) => {
111
111
 
112
112
  The return value of the `action` function can be any serializable content or a [Fetch Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) instance. You can access the content via [`useActionData`](https://reactrouter.com/en/main/hooks/use-action-data).
113
113
 
114
+ ### Redirects
115
+
116
+ An action can return or throw `redirect('/dashboard')` imported from `@modern-js/runtime/router` to navigate after a submission. This also applies to submissions made with `useFetcher`.
117
+
118
+ Actions run when a form or `submit` triggers a mutation request. Visiting a route alone does not run its action. To redirect when loading a route, use `redirect` in its loader.
119
+
114
120
  ## useSubmit and useFetcher
115
121
 
116
122
  ### Difference
@@ -85,6 +85,37 @@ If you use Rush as your Monorepo management tool, you can add the following comm
85
85
 
86
86
  After the build is completed, Modern.js will generate all dependencies in the `.output/node_modules` directory of the project. Similarly, you can run the Modern.js server using `node .output/index`.
87
87
 
88
+ ### Production server logs
89
+
90
+ The built-in Node.js production server defaults to the `info` log level. It prints informational messages, warnings and errors, without logging every page or static asset request.
91
+
92
+ Set `MODERN_SERVER_LOG_LEVEL` when starting the server to change its log level:
93
+
94
+ ```bash
95
+ MODERN_SERVER_LOG_LEVEL=warn node .output/index
96
+ ```
97
+
98
+ The supported values are the [rslog](https://github.com/rstackjs/rslog) log levels:
99
+
100
+ | Value | Output |
101
+ | --------- | ------------------------------------------------------------------- |
102
+ | `silent` | No logs |
103
+ | `error` | Errors only |
104
+ | `warn` | Warnings and errors |
105
+ | `info` | Informational messages, warnings and errors (default) |
106
+ | `log` | Everything at `info`, plus messages written with `logger.log()` |
107
+ | `verbose` | All logs, including debug messages, request logs and timing details |
108
+
109
+ To enable per-request logs, including static asset requests:
110
+
111
+ ```bash
112
+ MODERN_SERVER_LOG_LEVEL=verbose node .output/index
113
+ ```
114
+
115
+ Setting `DEBUG` to a non-empty value also enables `verbose` logging, unless `MODERN_SERVER_LOG_LEVEL` explicitly selects another level.
116
+
117
+ This environment variable controls the built-in server logger. It does not override a custom logger or enable logging when `server.logger` is `false`.
118
+
88
119
  ## Netlify
89
120
 
90
121
  Netlify is a popular Web development platform designed for building, deploying, and maintaining modern web projects. Deploying on Netlify mainly requires configuring the `netlify.toml` file.
@@ -114,6 +114,64 @@ export default defineConfig({
114
114
  });
115
115
  ```
116
116
 
117
+ ## SSG Matching for Parent and Child Routes
118
+
119
+ For a blog, `src/routes/blog/page.tsx` renders the list and `src/routes/blog/[slug]/page.tsx` renders an article. After enabling SSG, you can prerender both the list and selected articles:
120
+
121
+ {/* prettier-ignore */}
122
+ ```ts title="modern.config.ts"
123
+ export default defineConfig({
124
+ output: {
125
+ ssg: {
126
+ routes: ['/blog', '/blog/hello'],
127
+ },
128
+ },
129
+ })
130
+ ```
131
+
132
+ Each path generates its own static HTML. The built-in production server matches SSG pages by their exact paths:
133
+
134
+ | Request path | Behavior |
135
+ | ---------------------- | --------------------------------------------------------------- |
136
+ | `/blog` | Returns the static HTML for the blog list |
137
+ | `/blog/hello` | Returns the static HTML for the article |
138
+ | `/blog/does-not-exist` | Does not match an SSG page and falls back to an available entry |
139
+
140
+ Requests to a trailing-slash URL such as `/blog/` receive an HTTP 308 redirect to `/blog`, preserving the query string. For example, `/blog/?preview=1` redirects to `/blog?preview=1`.
141
+
142
+ The SSG page at `/blog` does not act as a fallback for `/blog/*`. Defining a `[slug]` route does not automatically generate static HTML for every slug. List the concrete paths in `routes`.
143
+
144
+ This example does not enable SSR or prerender the root entry `/`. An unmatched path therefore receives the root entry's CSR shell, and routing continues in the browser. The initial HTML response is typically HTTP 200. An unknown slug alone does not cause the server to return 404.
145
+
146
+ If a matching SSR entry exists, SSR determines the response content and status. If no entry matches, the server returns 404. If you also configure the root entry `/` for SSG, it only matches its own path and no longer provides a wildcard fallback.
147
+
148
+ ## Handling 404 Responses During Prerendering
149
+
150
+ Continuing the example, suppose you add `/blog/scheduled` to `output.ssg.routes`, but the article has not been published yet. Its loader can throw a 404 during the build. Here, `getPost` is your application's article lookup function, and `publishedAt` is the publication timestamp in milliseconds:
151
+
152
+ {/* prettier-ignore */}
153
+ ```ts title="src/routes/blog/[slug]/page.data.ts"
154
+ import { getPost } from '@/data/posts'
155
+
156
+ export const loader = async ({ params }: { params: { slug: string } }) => {
157
+ const post = await getPost(params.slug)
158
+ if (!post || post.publishedAt > Date.now()) {
159
+ throw new Response('Not Found', { status: 404 })
160
+ }
161
+ return post
162
+ }
163
+ ```
164
+
165
+ When prerendering returns 404 or another non-2xx response, the build:
166
+
167
+ - Logs a warning containing the path and status code.
168
+ - Skips the page's static HTML file and SSG route registration.
169
+ - Continues generating pages with successful responses.
170
+
171
+ The error page is therefore not saved as static HTML that would later be served with HTTP 200. Requests to `/blog/scheduled` follow the entry fallback rules above. The build-time 404 is not stored as the path's runtime response status.
172
+
173
+ SSG only generates pages during a build. Reaching the publication time does not automatically generate the missing static HTML. Rebuild and redeploy to generate the article's SSG page.
174
+
117
175
  ## Multi-entry
118
176
 
119
177
  For multi-entry apps, configure per entry via `output.ssgByEntries`:
@@ -87,6 +87,24 @@ Modern.js 3.0 uses React Router v7 as the default routing library. React Router
87
87
 
88
88
  If you need to use React Router v5 or React Router v6, you need to use **self-controlled routing** mode. Self-controlled routing allows you to fully control routing configuration without being limited by Modern.js convention-based routing.
89
89
 
90
+ ### Router updates use transitions by default
91
+
92
+ React Router v7 wraps router state updates in `React.startTransition` by default. In v6 this behavior required enabling `future.v7_startTransition`. After upgrading, the page mount after the initial Data Loader finishes and every navigation switch from synchronous rendering to concurrent rendering. A render may be discarded and run again, and there may be a gap between render and commit.
93
+
94
+ If your project changes external state during render, you may see the following issues after upgrading:
95
+
96
+ - An instance is created in `useMemo` and assigned to a global variable. After it runs again, multiple instances exist and logic that relies on a singleton throws.
97
+ - A React Router v6 `RouterProvider` is nested inside a page. It reads the router state during render but only subscribes in `useLayoutEffect`, so it may miss the initialization notification and the page stays blank. See [React Router issue #14356](https://github.com/remix-run/react-router/issues/14356).
98
+
99
+ Keep render free of side effects as React requires:
100
+
101
+ - Create instances, register listeners, send analytics, and modify global variables in `useEffect`.
102
+ - Read external state with [`useSyncExternalStore`](https://react.dev/reference/react/useSyncExternalStore).
103
+ - Create objects such as routers and stores outside components.
104
+ - Enable `StrictMode` in development to surface code that breaks when run twice.
105
+
106
+ If your code cannot be refactored yet, set [`router.useTransitions`](/configure/app/runtime/router#usetransitions) to `false` to restore synchronous rendering.
107
+
90
108
  ## Using @modern-js/create to Create Monorepo and Modern.js Module
91
109
 
92
110
  Modern.js 3.0 no longer supports creating Monorepo projects and Modern.js Module projects through `@modern-js/create`.
@@ -37,3 +37,40 @@ title: router
37
37
  当开启 SSR 时,不支持设置 `supportHtml5History`。
38
38
 
39
39
  :::
40
+
41
+ ## useTransitions
42
+
43
+ - **类型:** `boolean`
44
+ - **默认值:** `undefined`,与 React Router 的默认行为一致,即开启
45
+
46
+ 是否用 [`React.startTransition`](https://react.dev/reference/react/startTransition) 包裹路由状态更新。该值会透传给 React Router 的 [`<RouterProvider useTransitions>`](https://reactrouter.com/api/data-routers/RouterProvider)。
47
+
48
+ 开启时,首屏 Data Loader 完成后的页面挂载和每次路由跳转都以并发方式渲染,好处是:
49
+
50
+ - 跳转时在新页面准备好之前保留旧页面,不会先显示加载状态。
51
+ - 渲染过程可以让出主线程,页面切换期间仍能响应用户输入。
52
+
53
+ 同时会带来两个与同步渲染不同的行为:
54
+
55
+ - 渲染可能被丢弃后重新执行。组件函数体、`useMemo` 和 `useState` 的初始化函数、类组件构造函数可能执行多次,其中修改外部状态的代码(例如创建实例并赋值给全局变量、注册事件监听、上报埋点)也会重复执行。
56
+ - 渲染与提交之间可能有间隔。渲染时读取的外部状态,到 `useLayoutEffect` 中订阅时可能已经变化,间隔内发生的更新会丢失。
57
+
58
+ 如果应用中存在上述写法且暂时无法改造,可以设置为 `false`,路由状态更新会改为同步渲染:
59
+
60
+ ```ts title="src/modern.runtime.ts"
61
+ import { defineRuntimeConfig } from '@modern-js/runtime';
62
+
63
+ export default defineRuntimeConfig({
64
+ router: {
65
+ useTransitions: false,
66
+ },
67
+ });
68
+ ```
69
+
70
+ :::tip
71
+
72
+ - 该配置只影响路由状态更新。在业务代码中调用 `startTransition` 或 `useTransition` 触发的更新不受影响。
73
+ - 改造方式可参考 [React Router 文档](https://reactrouter.com/explanation/react-transitions)。
74
+ - `future.v7_startTransition` 已废弃。未设置 `useTransitions` 时,会使用 `future.v7_startTransition` 的值。
75
+
76
+ :::
@@ -16,7 +16,7 @@ npx @modern-js/create@latest my-mf-mcp --template mcp-apps --mf
16
16
 
17
17
  ## 声明卡片
18
18
 
19
- 创建 `mcp-views.json`。字符串路径相对该 JSON 文件解析。对象仅支持引用本项目 MF 配置中已有的 expose。
19
+ 创建 `mcp-views.json`。字符串路径相对该 JSON 文件解析。对象可以引用本项目 MF 配置中已有的 expose,也可以通过 `remote` 引用已部署的远程模块,见下文。
20
20
 
21
21
  ```json
22
22
  {
@@ -45,6 +45,31 @@ mcpAppsPlugin({
45
45
  });
46
46
  ```
47
47
 
48
+ ### 引用已部署的远程模块
49
+
50
+ 卡片由另一个项目作为 MF 远程模块发布时,用 `remote` 指定远程模块的 manifest 地址:
51
+
52
+ ```json
53
+ {
54
+ "remote": "https://ui.example.com/mf-manifest.json",
55
+ "views": {
56
+ "todos": { "expose": "./Todos" },
57
+ "stats": { "expose": "./Stats" }
58
+ },
59
+ "csp": { "resourceDomains": ["https://cdn.example.com"] }
60
+ }
61
+ ```
62
+
63
+ 顶层 `remote` 与 `csp` 同级,供所有 expose 视图共用。单个视图可配置 `remote` 覆盖默认值。字符串路径仍引用本地组件。顶层和视图都未配置 `remote` 时,expose 引用本项目。配置顶层 `remote` 后,同一份配置中的 expose 视图无法再引用本项目的 expose。需要混用时,不配置顶层 `remote`,只在引用远程模块的视图上配置。
64
+
65
+ - 地址必须是绝对的 HTTP(S) 地址,路径以 `.json` 结尾。不支持直接引用 `remoteEntry.js` 等非 manifest 入口
66
+ - 不需要填写远程模块的名称,运行时从 manifest 读取
67
+ - shell 在卡片打开时读取远程 manifest 并加载 expose。远程模块重新发布后,MCP 服务无需重新构建或重启。构建时不检查 expose 是否存在,缺失时卡片显示加载错误
68
+ - 本项目不需要启用 MF 插件,但需要安装 `mf.runtime` 指定的运行时。远程模块使用其他 MF 实现时,按上文设置 `mf.runtime`
69
+ - manifest 所在的 origin 会自动加入 CSP。远程模块的脚本和样式由其他域名(例如 CDN)提供时,需要在 `csp.resourceDomains` 中声明。manifest 和脚本需允许跨域访问
70
+ - 远程模块需把 React 声明为 singleton 共享依赖,与 shell 共用同一份 React
71
+ - 新增卡片或修改 `remote`、`expose` 时,仍需重新构建 MCP 服务
72
+
48
73
  本地卡片以独立入口构建,不加载框架的页面运行时。`source.enableAsyncEntry` 开启时,入口通过动态 import 建立异步边界,供 MF 共享依赖完成初始化。MF 插件会自动开启该选项。未开启时直接挂载卡片,不增加额外请求。
49
74
 
50
75
  卡片必须默认导出 React 组件。props 来自 tool 返回的 `structuredContent`,`mcpApp` 为框架保留的注入字段。
@@ -17,3 +17,5 @@
17
17
  import InternalLogger from '@site-docs/components/internal-logger.mdx';
18
18
 
19
19
  <InternalLogger />
20
+
21
+ 如需通过 `MODERN_SERVER_LOG_LEVEL` 配置内置生产服务器的日志级别,请参阅[生产服务器日志](../../basic-features/deploy#生产服务器日志)。
@@ -111,6 +111,12 @@ export const action = async ({ request }: ActionFunctionArgs) => {
111
111
  `action` 函数的返回值可以是任何可序列化的内容,也可以是一个 [Fetch Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) 实例,
112
112
  可以通过 [`useActionData`](https://reactrouter.com/en/main/hooks/use-action-data) 访问 response 中内容。
113
113
 
114
+ ### 重定向
115
+
116
+ 在 action 中,可以从 `@modern-js/runtime/router` 导入 `redirect`,通过 `return redirect('/dashboard')` 或 `throw redirect('/dashboard')` 在提交后跳转。这也适用于通过 `useFetcher` 发起的提交。
117
+
118
+ action 在表单或 `submit` 发起数据写入请求时执行。仅访问路由不会触发 action。如果需要在加载路由时重定向,请在 loader 中使用 `redirect`。
119
+
114
120
  ## useSubmit 和 useFetcher
115
121
 
116
122
  ### 区别
@@ -84,6 +84,37 @@ PORT=3000 node .output/index
84
84
 
85
85
  构建完成后,框架会将项目中所有的依赖生成在 `.output/node_modules` 目录下。你同样可以使用 `node .output/index` 运行 Modern.js 服务器。
86
86
 
87
+ ### 生产服务器日志
88
+
89
+ 内置 Node.js 生产服务器默认使用 `info` 日志级别,输出普通信息、警告和错误,不会为每个页面请求或静态资源请求打印日志。
90
+
91
+ 启动服务器时,可以通过 `MODERN_SERVER_LOG_LEVEL` 调整日志级别:
92
+
93
+ ```bash
94
+ MODERN_SERVER_LOG_LEVEL=warn node .output/index
95
+ ```
96
+
97
+ 支持的值与 [rslog](https://github.com/rstackjs/rslog) 的日志级别一致:
98
+
99
+ | 值 | 输出内容 |
100
+ | --------- | --------------------------------------------------------- |
101
+ | `silent` | 不输出日志 |
102
+ | `error` | 仅错误 |
103
+ | `warn` | 警告和错误 |
104
+ | `info` | 普通信息、警告和错误,默认值 |
105
+ | `log` | `info` 级别的全部日志,以及通过 `logger.log()` 输出的信息 |
106
+ | `verbose` | 全部日志,包括调试信息、请求日志和耗时信息 |
107
+
108
+ 如果需要逐请求日志,包括静态资源请求日志,可以使用:
109
+
110
+ ```bash
111
+ MODERN_SERVER_LOG_LEVEL=verbose node .output/index
112
+ ```
113
+
114
+ 将 `DEBUG` 设置为非空值也会启用 `verbose` 日志。如果同时设置了 `MODERN_SERVER_LOG_LEVEL`,则优先使用后者指定的级别。
115
+
116
+ 该环境变量仅控制内置的服务器 logger,不会覆盖自定义 logger,也不会在 `server.logger` 为 `false` 时启用日志。
117
+
87
118
  ## Netlify
88
119
 
89
120
  Netlify 是一个流行的 Web 开发平台,专为构建、发布和维护现代 Web 项目而设计。在 Netlify 上部署,通常需要配置 `netlify.toml` 文件,你可以根据项目复杂度,渐进地配置该文件。
@@ -115,6 +115,64 @@ export default defineConfig({
115
115
  });
116
116
  ```
117
117
 
118
+ ## 父子路由的 SSG 匹配
119
+
120
+ 以博客为例,`src/routes/blog/page.tsx` 是列表页,`src/routes/blog/[slug]/page.tsx` 是文章页。启用 SSG 后,可以同时预渲染列表页和指定的文章页:
121
+
122
+ {/* prettier-ignore */}
123
+ ```ts title="modern.config.ts"
124
+ export default defineConfig({
125
+ output: {
126
+ ssg: {
127
+ routes: ['/blog', '/blog/hello'],
128
+ },
129
+ },
130
+ })
131
+ ```
132
+
133
+ 两条路径分别生成自己的静态 HTML。使用内置生产服务器访问时,SSG 页面按路径精确匹配:
134
+
135
+ | 请求路径 | 处理方式 |
136
+ | ---------------------- | --------------------------------- |
137
+ | `/blog` | 返回博客列表页的静态 HTML |
138
+ | `/blog/hello` | 返回文章页的静态 HTML |
139
+ | `/blog/does-not-exist` | 未命中 SSG 页面,交给可用入口处理 |
140
+
141
+ 访问 `/blog/` 这样的尾部斜杠形式时,服务器会通过 HTTP 308 重定向到 `/blog`,并保留查询参数。例如,`/blog/?preview=1` 会重定向到 `/blog?preview=1`。
142
+
143
+ `/blog` 的 SSG 页面不会作为 `/blog/*` 的回退页面。即使应用定义了 `[slug]` 动态路由,也不会自动为所有 slug 生成静态 HTML,需要在 `routes` 中列出具体路径。
144
+
145
+ 上例没有启用 SSR,也没有预渲染根入口 `/`,因此未命中的路径会返回根入口的 CSR 页面壳,由浏览器中的路由继续处理。此时初始 HTML 响应通常为 HTTP 200,不会因为路径中包含未知 slug 就在服务端返回 404。
146
+
147
+ 如果存在匹配的 SSR 入口,则由 SSR 渲染决定响应内容和状态码。没有可用入口时,服务器返回 404。如果将根入口 `/` 也配置为 SSG,它同样只匹配自身,不再提供通配回退。
148
+
149
+ ## 处理预渲染时的 404
150
+
151
+ 继续上例,如果将 `/blog/scheduled` 加入 `output.ssg.routes`,但文章尚未发布,loader 可以在构建时抛出 404。以下示例中,`getPost` 是业务侧的文章查询函数,`publishedAt` 是以毫秒为单位的发布时间戳:
152
+
153
+ {/* prettier-ignore */}
154
+ ```ts title="src/routes/blog/[slug]/page.data.ts"
155
+ import { getPost } from '@/data/posts'
156
+
157
+ export const loader = async ({ params }: { params: { slug: string } }) => {
158
+ const post = await getPost(params.slug)
159
+ if (!post || post.publishedAt > Date.now()) {
160
+ throw new Response('Not Found', { status: 404 })
161
+ }
162
+ return post
163
+ }
164
+ ```
165
+
166
+ 预渲染收到 404 或其他非 2xx 响应时,会:
167
+
168
+ - 输出包含路径和状态码的构建警告。
169
+ - 跳过该页面的静态 HTML 文件和 SSG 路由注册。
170
+ - 继续生成其他正常响应的页面。
171
+
172
+ 因此,错误页面不会被保存成之后以 HTTP 200 返回的静态页面。访问 `/blog/scheduled` 时,会按照上一节的入口回退规则处理,构建时的 404 不会被保存为该路径的运行时响应状态。
173
+
174
+ SSG 只在构建时生成页面,文章到达发布时间后不会自动补生成静态 HTML。需要重新构建并部署,才能生成该文章的 SSG 页面。
175
+
118
176
  ## 多入口
119
177
 
120
178
  多入口应用请通过 `output.ssgByEntries` 按入口分别配置:
@@ -87,6 +87,24 @@ Modern.js 3.0 默认使用 React Router v7 作为路由库。React Router v7 相
87
87
 
88
88
  如果需要使用 React Router v5 或 React Router v6,需要使用**自控式路由**模式。自控式路由允许你完全控制路由配置,不受 Modern.js 约定式路由的限制。
89
89
 
90
+ ### 路由更新默认使用 transition
91
+
92
+ React Router v7 默认用 `React.startTransition` 包裹路由状态更新,在 v6 中需要开启 `future.v7_startTransition` 才有这一行为。升级后,首屏 Data Loader 完成后的页面挂载和路由跳转会从同步渲染变为并发渲染,渲染可能被丢弃后重新执行,渲染与提交之间也可能有间隔。
93
+
94
+ 如果项目在渲染过程中修改外部状态,升级后可能出现以下问题:
95
+
96
+ - 在 `useMemo` 中创建实例并赋值给全局变量,重复执行后出现多个实例,依赖单例的逻辑报错。
97
+ - 在页面内嵌套使用 React Router v6 的 `RouterProvider`。它在渲染时读取 router 状态、在 `useLayoutEffect` 中才订阅,可能错过初始化完成的通知,页面一直显示空白,参考 [React Router issue #14356](https://github.com/remix-run/react-router/issues/14356)。
98
+
99
+ 推荐按 React 的要求保持渲染过程没有副作用:
100
+
101
+ - 创建实例、注册监听、上报埋点、修改全局变量等操作放到 `useEffect` 中执行。
102
+ - 读取外部状态使用 [`useSyncExternalStore`](https://react.dev/reference/react/useSyncExternalStore)。
103
+ - router、store 等对象在组件外创建。
104
+ - 开发环境开启 `StrictMode`,提前暴露重复执行的问题。
105
+
106
+ 如果暂时无法改造,可以将 [`router.useTransitions`](/configure/app/runtime/router#usetransitions) 设置为 `false`,恢复同步渲染。
107
+
90
108
  ## 使用 @modern-js/create 创建 Monorepo 和 Modern.js Module
91
109
 
92
110
  Modern.js 3.0 不再支持通过 `@modern-js/create` 创建 Monorepo 项目和 Modern.js Module 项目。
package/package.json CHANGED
@@ -16,14 +16,14 @@
16
16
  "modern",
17
17
  "modern.js"
18
18
  ],
19
- "version": "3.11.0",
19
+ "version": "3.11.2",
20
20
  "publishConfig": {
21
21
  "registry": "https://registry.npmjs.org/",
22
22
  "access": "public"
23
23
  },
24
24
  "dependencies": {
25
25
  "mermaid": "^11.17.2",
26
- "@modern-js/sandpack-react": "3.11.0"
26
+ "@modern-js/sandpack-react": "3.11.2"
27
27
  },
28
28
  "devDependencies": {
29
29
  "@rsbuild/plugin-sass": "2.0.1",