@modern-js/main-doc 3.10.4 → 3.11.1
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.
- package/docs/en/configure/app/runtime/router.mdx +37 -0
- package/docs/en/guides/advanced-features/_meta.json +1 -1
- package/docs/en/guides/advanced-features/mcp-apps.mdx +157 -0
- package/docs/en/guides/advanced-features/server-monitor/logger.mdx +2 -0
- package/docs/en/guides/basic-features/data/data-write.mdx +6 -0
- package/docs/en/guides/basic-features/deploy.mdx +31 -0
- package/docs/en/guides/basic-features/render/ssg.mdx +58 -0
- package/docs/en/guides/upgrade/other.mdx +18 -0
- package/docs/zh/configure/app/runtime/router.mdx +37 -0
- package/docs/zh/guides/advanced-features/_meta.json +1 -1
- package/docs/zh/guides/advanced-features/mcp-apps.mdx +190 -0
- package/docs/zh/guides/advanced-features/server-monitor/logger.mdx +2 -0
- package/docs/zh/guides/basic-features/data/data-write.mdx +6 -0
- package/docs/zh/guides/basic-features/deploy.mdx +31 -0
- package/docs/zh/guides/basic-features/render/ssg.mdx +58 -0
- package/docs/zh/guides/upgrade/other.md +18 -0
- package/package.json +2 -2
|
@@ -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
|
+
:::
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
# MCP Apps
|
|
2
|
+
|
|
3
|
+
Modern.js builds React cards for MCP hosts. UI builds and servers exchange only `ui-manifest.json`. Servers use the official MCP SDK directly.
|
|
4
|
+
|
|
5
|
+
## Create a project
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npx @modern-js/create@latest my-mcp --template mcp-apps
|
|
9
|
+
npx @modern-js/create@latest my-mf-mcp --template mcp-apps --mf
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Choose a release containing MCP Apps support. Run `pnpm dev`. The explicit BFF route is `/api/mcp`.
|
|
13
|
+
|
|
14
|
+
`@modern-js/mcp-apps` provides the build plugin, server plugin, server adapters and card runtime through `./cli`, `./server-plugin`, `./server` and `./react`. The application must install the peers `react`, `react-dom`, `@modelcontextprotocol/server` and `@modelcontextprotocol/ext-apps`, so cards use the application's React and tools, resources and HTTP handling use the application's SDK versions. `@modern-js/server-runtime` and `@module-federation/enhanced` are optional peers that provide the default request context for BFF handlers and the default MF shell runtime. The project templates already declare these dependencies.
|
|
15
|
+
|
|
16
|
+
## Build cards
|
|
17
|
+
|
|
18
|
+
Declare local default-export React components or this project's MF exposes in `mcp-views.json`:
|
|
19
|
+
|
|
20
|
+
```json
|
|
21
|
+
{
|
|
22
|
+
"views": {
|
|
23
|
+
"todos": "./src/components/Todos.tsx",
|
|
24
|
+
"stats": { "expose": "./Stats" }
|
|
25
|
+
},
|
|
26
|
+
"csp": { "resourceDomains": [], "connectDomains": [] },
|
|
27
|
+
"prefersBorder": true
|
|
28
|
+
}
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Import `mcpAppsPlugin` from `@modern-js/mcp-apps/cli` and add `mcpAppsPlugin({ views: './mcp-views.json' })` to your Modern.js plugins. Paths resolve relative to the JSON file. MF cards require the Modern.js MF plugin with manifest output enabled. The UI plugin validates exposes against the actual emitted MF manifest and builds the shell with the application's React dependencies.
|
|
32
|
+
|
|
33
|
+
The plugin finds the MF manifest in the web build output by filename, `mf-manifest.json` by default, and requires exactly one match. The shell imports `createInstance` from `@module-federation/enhanced/runtime` by default. Other MF implementations can replace both through the `mf` option:
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
mcpAppsPlugin({
|
|
37
|
+
views: './mcp-views.json',
|
|
38
|
+
mf: {
|
|
39
|
+
// MF manifest filename in the build output
|
|
40
|
+
manifestFile: 'vmok-manifest.json',
|
|
41
|
+
// Resolved from the application. Must export a compatible createInstance
|
|
42
|
+
runtime: '@vmok/kit/runtime',
|
|
43
|
+
},
|
|
44
|
+
});
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
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
|
+
|
|
49
|
+
{/* prettier-ignore */}
|
|
50
|
+
```tsx
|
|
51
|
+
import type { McpViewProps } from '@modern-js/mcp-apps/react'
|
|
52
|
+
|
|
53
|
+
export default function Todos({
|
|
54
|
+
todos = [],
|
|
55
|
+
mcpApp,
|
|
56
|
+
}: McpViewProps<{ todos: string[] }>) {
|
|
57
|
+
return (
|
|
58
|
+
<section>
|
|
59
|
+
<ul>
|
|
60
|
+
{todos.map(todo => (
|
|
61
|
+
<li key={todo}>{todo}</li>
|
|
62
|
+
))}
|
|
63
|
+
</ul>
|
|
64
|
+
<button
|
|
65
|
+
onClick={() =>
|
|
66
|
+
mcpApp.callServerTool({ name: 'refresh', arguments: {} })
|
|
67
|
+
}
|
|
68
|
+
>
|
|
69
|
+
Refresh
|
|
70
|
+
</button>
|
|
71
|
+
</section>
|
|
72
|
+
)
|
|
73
|
+
}
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Props come from successful `structuredContent`. The reserved `mcpApp` prop is injected by the wrapper. Input arguments are not merged into props. New input, cancellation and teardown clear previous output. The wrapper manages connection, host styling and loading/error states. Results from tools called inside a card must be handled by the component itself.
|
|
77
|
+
|
|
78
|
+
## Write the server
|
|
79
|
+
|
|
80
|
+
Enable `bffPlugin()` and create `api/lambda/mcp.ts`. The UI plugin does not register any HTTP route.
|
|
81
|
+
|
|
82
|
+
{/* prettier-ignore */}
|
|
83
|
+
```ts
|
|
84
|
+
import { McpServer } from '@modelcontextprotocol/server'
|
|
85
|
+
import { registerAppTool } from '@modelcontextprotocol/ext-apps/server'
|
|
86
|
+
import {
|
|
87
|
+
createBffHandlers,
|
|
88
|
+
registerUiResources,
|
|
89
|
+
} from '@modern-js/mcp-apps/server'
|
|
90
|
+
import { z } from 'zod'
|
|
91
|
+
|
|
92
|
+
async function createServer(request: Request) {
|
|
93
|
+
const server = new McpServer({ name: 'todos', version: '1.0.0' })
|
|
94
|
+
const ui = await registerUiResources(server, { request })
|
|
95
|
+
registerAppTool(
|
|
96
|
+
server,
|
|
97
|
+
'list_todos',
|
|
98
|
+
{
|
|
99
|
+
inputSchema: z.object({}),
|
|
100
|
+
_meta: { ui: { resourceUri: ui.todos } },
|
|
101
|
+
},
|
|
102
|
+
async () => ({
|
|
103
|
+
content: [{ type: 'text', text: 'Todo list' }],
|
|
104
|
+
structuredContent: { todos: ['Read the MCP Apps guide'] },
|
|
105
|
+
}),
|
|
106
|
+
)
|
|
107
|
+
return server
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export const { POST, GET, DELETE } = createBffHandlers(createServer)
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
The adapter reconstructs BFF's consumed JSON body and returns the SDK Response. It reads the raw request through `useHonoContext` from `@modern-js/server-runtime`. Frameworks built on Modern.js can pass their own implementation with `createBffHandlers(createServer, { useContext })`. The official SDK owns protocol serving and tool validation. Serving is stateless, so unsupported session operations such as GET and DELETE are rejected by the SDK. Return a fresh server per request. Put authentication and authorization in surrounding middleware or the factory, and persist business data in an external store.
|
|
114
|
+
|
|
115
|
+
For independent Hono servers, create `handle = createFetchHandler(createServer)` and mount `app.all('/mcp', c => handle(c.req.raw))`. Foreign browser origins are rejected unless listed in `allowedOrigins` in the adapter's second argument.
|
|
116
|
+
|
|
117
|
+
## Manifest and deployment
|
|
118
|
+
|
|
119
|
+
Builds emit `dist/mcp-apps/ui-manifest.json` and `dist/mcp-apps/ui/*.html`. Static JavaScript, CSS and MF files remain in the application's standard output. MF-only projects also emit a UI manifest. Local HTML filenames use a stable hash of the view name. MF cards share `mcp-shell.html`.
|
|
120
|
+
|
|
121
|
+
The version 1 manifest contains `assetBase`, `remotes` and `views`. A local view has `{ html, ui }`. An MF view has `{ remote, expose, ui }`, with its remote declaring `{ entry, shell }`.
|
|
122
|
+
|
|
123
|
+
- HTML and shell paths resolve relative to the manifest location
|
|
124
|
+
- MF entry paths resolve relative to `assetBase`
|
|
125
|
+
- Absolute HTTP(S) sources are supported for independent deployments
|
|
126
|
+
- `ui` preserves CSP, permissions, domain and border preferences
|
|
127
|
+
- Resource URIs are generated as `ui://app/<encoded-view-name>` by the server, and multiple tools can share a card
|
|
128
|
+
- MF configuration is injected into resource HTML instead of tool results
|
|
129
|
+
|
|
130
|
+
`createBffHandlers()` associates the server plugin’s manifest path and runtime mode with the current request. Call `registerUiResources(server, { request })` to resolve them automatically. Development uses the framework internal directory and production uses the runtime output directory. Explicit options override injected configuration. Independent services must provide a `manifest` file path or HTTP(S) URL. The `mode` option defaults to `production`. Relative HTML resolves against the manifest location.
|
|
131
|
+
|
|
132
|
+
Manifests are cached by source URL and environment. Production caches successful loads for the process lifetime, so updating the same location requires a process restart. Development detects local file changes and caches remote manifests for 60 seconds. Concurrent loads are coalesced and failures can be retried. HTML is read per resource request, and request-specific URLs and metadata remain isolated.
|
|
133
|
+
|
|
134
|
+
An absolute `output.assetPrefix` becomes `assetBase`. Otherwise request-origin resolution is used. Override `assetBase` in `registerUiResources` for a separate static origin or deployment path prefix. Request mode honors sanitized `x-forwarded-proto` headers. Reverse proxies must preserve the public host and sanitize forwarded headers.
|
|
135
|
+
|
|
136
|
+
Required asset, connection and base URI origins are added to CSP. MF entry origins are also added to connection permissions. The origin of an absolute or protocol-relative `output.assetPrefix` is added at build time, with `//cdn.example/` treated as `https://cdn.example`. Declare any other API, chunk/CDN or iframe origins in `mcp-views.json`, or pass domains computed in the config through `mcpAppsPlugin({ csp })`. Both are merged into every view. Deploy the manifest and HTML together with the application static assets and MF output.
|
|
137
|
+
|
|
138
|
+
Platforms may rewrite file and MF addresses to absolute URLs and combine cards into another manifest of the same version. Unknown versions are rejected.
|
|
139
|
+
|
|
140
|
+
## Card capabilities
|
|
141
|
+
|
|
142
|
+
Cards advertise `inline` and `fullscreen` by default. Both local component modules and MF exposes can export `mcpCapabilities` to declare additional capabilities or override the display modes.
|
|
143
|
+
|
|
144
|
+
{/* prettier-ignore */}
|
|
145
|
+
```tsx
|
|
146
|
+
import type { McpCapabilities } from '@modern-js/mcp-apps/react'
|
|
147
|
+
|
|
148
|
+
export const mcpCapabilities = {
|
|
149
|
+
availableDisplayModes: ['inline'],
|
|
150
|
+
} satisfies McpCapabilities
|
|
151
|
+
|
|
152
|
+
export default function Card() {
|
|
153
|
+
return <div>My card</div>
|
|
154
|
+
}
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
You can also pass capabilities as the third argument to `createMcpView`. Explicit display mode arrays replace the defaults. MF modules are loaded before initialization so the handshake includes their capabilities. Declaring fullscreen support does not add a fullscreen button or switch modes automatically.
|
|
@@ -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
|
+
:::
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
# MCP Apps
|
|
2
|
+
|
|
3
|
+
Modern.js 可以把 React 组件构建为 MCP 卡片。UI 构建与服务端通过 `ui-manifest.json` 关联,服务端直接使用官方 MCP SDK。
|
|
4
|
+
|
|
5
|
+
## 创建项目
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npx @modern-js/create@latest my-mcp --template mcp-apps
|
|
9
|
+
# 复用本项目的 Module Federation expose
|
|
10
|
+
npx @modern-js/create@latest my-mf-mcp --template mcp-apps --mf
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
使用包含 MCP Apps 支持的版本。运行 `pnpm dev` 后,MCP 地址为 `/api/mcp`。
|
|
14
|
+
|
|
15
|
+
构建插件、服务端插件、服务端适配器和卡片运行时都由 `@modern-js/mcp-apps` 提供,分别从 `./cli`、`./server-plugin`、`./server` 和 `./react` 导入。应用需安装 peer 依赖 `react`、`react-dom`、`@modelcontextprotocol/server` 和 `@modelcontextprotocol/ext-apps`,让卡片使用应用的 React,工具、资源注册和 HTTP 处理使用应用安装的 SDK。`@modern-js/server-runtime` 和 `@module-federation/enhanced` 是可选 peer,分别作为 BFF handler 获取请求上下文和 MF shell 运行时的默认实现。脚手架模板已声明这些依赖。
|
|
16
|
+
|
|
17
|
+
## 声明卡片
|
|
18
|
+
|
|
19
|
+
创建 `mcp-views.json`。字符串路径相对该 JSON 文件解析。对象仅支持引用本项目 MF 配置中已有的 expose。
|
|
20
|
+
|
|
21
|
+
```json
|
|
22
|
+
{
|
|
23
|
+
"views": {
|
|
24
|
+
"todos": "./src/components/Todos.tsx",
|
|
25
|
+
"stats": { "expose": "./Stats" }
|
|
26
|
+
},
|
|
27
|
+
"csp": { "resourceDomains": [], "connectDomains": [] },
|
|
28
|
+
"prefersBorder": true
|
|
29
|
+
}
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
在 `modern.config.ts` 中从 `@modern-js/mcp-apps/cli` 导入并加入 `mcpAppsPlugin({ views: './mcp-views.json' })`。本地卡片仅需该插件,MF 卡片还需启用 `@module-federation/modern-js-v3` 插件并开启 manifest 输出。插件读取实际 MF 构建产物,验证 expose 存在,生成项目自身构建的 shell。
|
|
33
|
+
|
|
34
|
+
插件按文件名在 web 构建产物中查找 MF manifest,默认为 `mf-manifest.json`,必须恰好匹配一个文件。shell 默认从 `@module-federation/enhanced/runtime` 导入 `createInstance`。使用其他 MF 实现时,可以通过 `mf` 参数替换:
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
mcpAppsPlugin({
|
|
38
|
+
views: './mcp-views.json',
|
|
39
|
+
mf: {
|
|
40
|
+
// 构建产物中 MF manifest 的文件名
|
|
41
|
+
manifestFile: 'vmok-manifest.json',
|
|
42
|
+
// 从应用解析,需导出兼容的 createInstance
|
|
43
|
+
runtime: '@vmok/kit/runtime',
|
|
44
|
+
},
|
|
45
|
+
});
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
本地卡片以独立入口构建,不加载框架的页面运行时。`source.enableAsyncEntry` 开启时,入口通过动态 import 建立异步边界,供 MF 共享依赖完成初始化。MF 插件会自动开启该选项。未开启时直接挂载卡片,不增加额外请求。
|
|
49
|
+
|
|
50
|
+
卡片必须默认导出 React 组件。props 来自 tool 返回的 `structuredContent`,`mcpApp` 为框架保留的注入字段。
|
|
51
|
+
|
|
52
|
+
{/* prettier-ignore */}
|
|
53
|
+
```tsx
|
|
54
|
+
import type { McpViewProps } from '@modern-js/mcp-apps/react'
|
|
55
|
+
|
|
56
|
+
export default function Todos({
|
|
57
|
+
todos = [],
|
|
58
|
+
mcpApp,
|
|
59
|
+
}: McpViewProps<{ todos: string[] }>) {
|
|
60
|
+
return (
|
|
61
|
+
<section>
|
|
62
|
+
<ul>
|
|
63
|
+
{todos.map(todo => (
|
|
64
|
+
<li key={todo}>{todo}</li>
|
|
65
|
+
))}
|
|
66
|
+
</ul>
|
|
67
|
+
<button
|
|
68
|
+
onClick={() =>
|
|
69
|
+
mcpApp.callServerTool({ name: 'refresh', arguments: {} })
|
|
70
|
+
}
|
|
71
|
+
>
|
|
72
|
+
刷新
|
|
73
|
+
</button>
|
|
74
|
+
</section>
|
|
75
|
+
)
|
|
76
|
+
}
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
默认包装器处理连接、主题、加载、错误、取消和 teardown。开始新一轮 tool 调用时会清空旧结果,不把输入参数合并进 props。卡片内调用 tool 返回的结果由组件自己处理,不会自动替换当前卡片数据。
|
|
80
|
+
|
|
81
|
+
## 编写服务端
|
|
82
|
+
|
|
83
|
+
创建 `api/lambda/mcp.ts`,使用官方 `McpServer`、`registerAppTool` 和 zod。UI 插件不自动挂载任何 MCP 路由。
|
|
84
|
+
|
|
85
|
+
{/* prettier-ignore */}
|
|
86
|
+
```ts
|
|
87
|
+
import { McpServer } from '@modelcontextprotocol/server'
|
|
88
|
+
import { registerAppTool } from '@modelcontextprotocol/ext-apps/server'
|
|
89
|
+
import {
|
|
90
|
+
createBffHandlers,
|
|
91
|
+
registerUiResources,
|
|
92
|
+
} from '@modern-js/mcp-apps/server'
|
|
93
|
+
import { z } from 'zod'
|
|
94
|
+
|
|
95
|
+
async function createServer(request: Request) {
|
|
96
|
+
const server = new McpServer({ name: 'todos', version: '1.0.0' })
|
|
97
|
+
const ui = await registerUiResources(server, { request })
|
|
98
|
+
registerAppTool(
|
|
99
|
+
server,
|
|
100
|
+
'list_todos',
|
|
101
|
+
{
|
|
102
|
+
inputSchema: z.object({}),
|
|
103
|
+
_meta: { ui: { resourceUri: ui.todos } },
|
|
104
|
+
},
|
|
105
|
+
async () => ({
|
|
106
|
+
content: [{ type: 'text', text: 'Todo list' }],
|
|
107
|
+
structuredContent: { todos: ['Read the MCP Apps guide'] },
|
|
108
|
+
}),
|
|
109
|
+
)
|
|
110
|
+
return server
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export const { POST, GET, DELETE } = createBffHandlers(createServer)
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
需要启用 `bffPlugin()`。适配器根据 BFF 已解析的 JSON 重建请求,返回 SDK 的原始 Response。适配器通过 `@modern-js/server-runtime` 的 `useHonoContext` 获取原始请求,基于 Modern.js 封装的框架可以通过 `createBffHandlers(createServer, { useContext })` 传入自己的实现。默认无状态 HTTP 模式由官方 SDK 处理协议和参数校验,GET、DELETE 等不支持的会话操作由 SDK 返回错误。认证与业务授权放在 HTTP 中间件或 `createServer` 中。每个请求创建独立的 server,业务数据需要持久化到外部存储。
|
|
117
|
+
|
|
118
|
+
独立 Hono 服务可通过 `app.all('/mcp', c => handle(c.req.raw))` 挂载 `createFetchHandler(createServer)`。适配器默认只允许同源浏览器请求,额外来源通过第二个参数的 `allowedOrigins` 配置。
|
|
119
|
+
|
|
120
|
+
## 清单与部署
|
|
121
|
+
|
|
122
|
+
```text
|
|
123
|
+
dist/
|
|
124
|
+
├─ mcp-apps/
|
|
125
|
+
│ ├─ ui-manifest.json
|
|
126
|
+
│ └─ ui/
|
|
127
|
+
│ ├─ mcp-ui-<name>-<hash>.html
|
|
128
|
+
│ └─ mcp-shell.html
|
|
129
|
+
└─ static/
|
|
130
|
+
└─ mf-manifest.json
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
本地卡片文件名由卡片名生成稳定 hash,避免文件名冲突与路径注入。MF 卡片共用 shell。
|
|
134
|
+
|
|
135
|
+
清单契约为:
|
|
136
|
+
|
|
137
|
+
```json
|
|
138
|
+
{
|
|
139
|
+
"version": 1,
|
|
140
|
+
"assetBase": "request",
|
|
141
|
+
"remotes": {
|
|
142
|
+
"todo_ui": {
|
|
143
|
+
"entry": "static/mf-manifest.json",
|
|
144
|
+
"shell": "./ui/mcp-shell.html"
|
|
145
|
+
}
|
|
146
|
+
},
|
|
147
|
+
"views": {
|
|
148
|
+
"todos": {
|
|
149
|
+
"html": "./ui/mcp-ui-local-25bf8e1a2393.html",
|
|
150
|
+
"ui": { "prefersBorder": true }
|
|
151
|
+
},
|
|
152
|
+
"stats": { "remote": "todo_ui", "expose": "./Stats", "ui": {} }
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
- `html`、`shell` 相对清单文件位置解析,也支持绝对 HTTP(S) 地址
|
|
158
|
+
- `entry` 相对 `assetBase` 解析,也支持绝对 HTTP(S) 地址
|
|
159
|
+
- `ui` 保留卡片的 CSP、permissions、domain、prefersBorder 元数据
|
|
160
|
+
- 清单不记录 tool 或 resource URI,服务端生成 `ui://app/<编码后的卡片名>`,多个 tool 可以复用同一 URI
|
|
161
|
+
- MF 配置在读取 resource 时注入 shell,不需要 tool result 携带框架元数据
|
|
162
|
+
|
|
163
|
+
`createBffHandlers()` 将服务端插件提供的清单路径和运行模式关联到当前请求。调用 `registerUiResources(server, { request })` 即可自动获取配置。开发使用框架的内部目录,生产使用运行时的实际输出目录。显式选项优先于注入配置。独立服务必须显式配置 `manifest` 文件路径或 HTTP(S) URL,`mode` 默认为 `production`。相对 HTML 路径以清单位置为基准解析。
|
|
164
|
+
|
|
165
|
+
清单按来源地址和环境缓存。生产环境在进程生命周期内复用,原地址更新清单后需重启进程。开发环境检查本地文件状态,文件变化后重新加载,远程清单缓存 60 秒。并发加载会合并,加载失败后允许重试。HTML 仍在读取资源时加载,请求相关的地址和 metadata 不会跨请求复用。
|
|
166
|
+
|
|
167
|
+
`output.assetPrefix` 为绝对地址时用于推导 `assetBase`。`request` 表示使用请求的公开 origin,支持经过代理清理的 `x-forwarded-proto`。子路径或外部静态资源部署可以通过 `registerUiResources` 的 `assetBase` 显式覆盖。反向代理必须保留公开 host 并清理转发头。
|
|
168
|
+
|
|
169
|
+
服务端把资源根地址加入 CSP 的 resourceDomains、connectDomains 和 baseUriDomains,把 MF entry 的 origin 加入 connectDomains 和 resourceDomains。构建时还会把绝对地址或不带协议的 `output.assetPrefix` 的 origin 加入 CSP,`//cdn.example/` 按 `https://cdn.example` 处理。其他 CDN、接口和 iframe 域名需在 `mcp-views.json` 中声明,或在配置中计算后通过 `mcpAppsPlugin({ csp })` 传入,两者都会合并到每张卡片。生产部署必须保留清单、HTML、应用静态资源和 MF 产物。
|
|
170
|
+
|
|
171
|
+
平台可以把已构建的卡片文件和 MF 地址转换为绝对地址,组合成同版本的新清单,再由独立服务端消费。未知清单版本会被拒绝。
|
|
172
|
+
|
|
173
|
+
## 卡片能力声明
|
|
174
|
+
|
|
175
|
+
卡片默认声明支持 `inline` 和 `fullscreen`。本地组件模块及 MF expose 都可以导出 `mcpCapabilities`,补充能力或覆盖展示模式。
|
|
176
|
+
|
|
177
|
+
{/* prettier-ignore */}
|
|
178
|
+
```tsx
|
|
179
|
+
import type { McpCapabilities } from '@modern-js/mcp-apps/react'
|
|
180
|
+
|
|
181
|
+
export const mcpCapabilities = {
|
|
182
|
+
availableDisplayModes: ['inline'],
|
|
183
|
+
} satisfies McpCapabilities
|
|
184
|
+
|
|
185
|
+
export default function Card() {
|
|
186
|
+
return <div>My card</div>
|
|
187
|
+
}
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
手动使用 `createMcpView` 时,也可以通过第三个参数传入能力声明。显式的展示模式数组会替换默认值。MF 模块在初始化前加载,确保握手包含该模块的能力。声明支持全屏不会自动添加全屏按钮或切换展示模式。
|
|
@@ -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.
|
|
19
|
+
"version": "3.11.1",
|
|
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.
|
|
26
|
+
"@modern-js/sandpack-react": "3.11.1"
|
|
27
27
|
},
|
|
28
28
|
"devDependencies": {
|
|
29
29
|
"@rsbuild/plugin-sass": "2.0.1",
|