@modern-js/main-doc 2.42.1 → 2.43.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (42) hide show
  1. package/docs/en/apis/app/runtime/web-server/middleware.mdx +3 -3
  2. package/docs/en/configure/app/server/ssr.mdx +2 -0
  3. package/docs/en/guides/advanced-features/inline-assets.mdx +161 -0
  4. package/docs/en/guides/advanced-features/optimize-bundle.mdx +8 -7
  5. package/docs/en/guides/advanced-features/ssr/_category_.json +8 -0
  6. package/docs/en/guides/advanced-features/ssr/cache.mdx +186 -0
  7. package/docs/en/guides/advanced-features/ssr/index.mdx +22 -0
  8. package/docs/en/guides/advanced-features/ssr/stream.mdx +236 -0
  9. package/docs/en/guides/advanced-features/ssr/usage.mdx +341 -0
  10. package/docs/en/guides/basic-features/alias.mdx +80 -2
  11. package/docs/en/guides/basic-features/css-modules.mdx +228 -0
  12. package/docs/en/guides/basic-features/css.mdx +2 -13
  13. package/docs/en/guides/basic-features/json-files.mdx +106 -0
  14. package/docs/en/guides/basic-features/output-files.mdx +173 -0
  15. package/docs/en/guides/basic-features/static-assets.mdx +165 -0
  16. package/docs/en/guides/basic-features/svg-assets.mdx +155 -0
  17. package/docs/en/guides/basic-features/wasm-assets.mdx +66 -0
  18. package/docs/en/guides/get-started/quick-start.mdx +1 -1
  19. package/docs/en/guides/get-started/tech-stack.mdx +1 -1
  20. package/docs/en/guides/topic-detail/framework-plugin/introduction.mdx +63 -16
  21. package/docs/zh/apis/app/runtime/web-server/middleware.mdx +4 -4
  22. package/docs/zh/configure/app/server/ssr.mdx +2 -0
  23. package/docs/zh/guides/advanced-features/inline-assets.mdx +162 -0
  24. package/docs/zh/guides/advanced-features/optimize-bundle.mdx +8 -7
  25. package/docs/zh/guides/advanced-features/ssr/_category_.json +8 -0
  26. package/docs/zh/guides/advanced-features/ssr/cache.mdx +189 -0
  27. package/docs/zh/guides/advanced-features/ssr/index.mdx +22 -0
  28. package/docs/zh/guides/advanced-features/ssr/stream.mdx +240 -0
  29. package/docs/zh/guides/advanced-features/{ssr.mdx → ssr/usage.mdx} +7 -225
  30. package/docs/zh/guides/basic-features/alias.mdx +80 -2
  31. package/docs/zh/guides/basic-features/css-modules.mdx +229 -0
  32. package/docs/zh/guides/basic-features/css.mdx +2 -13
  33. package/docs/zh/guides/basic-features/data/data-write.mdx +1 -1
  34. package/docs/zh/guides/basic-features/json-files.mdx +106 -0
  35. package/docs/zh/guides/basic-features/output-files.mdx +173 -0
  36. package/docs/zh/guides/basic-features/static-assets.mdx +165 -0
  37. package/docs/zh/guides/basic-features/svg-assets.mdx +157 -0
  38. package/docs/zh/guides/basic-features/wasm-assets.mdx +66 -0
  39. package/docs/zh/guides/get-started/quick-start.mdx +1 -1
  40. package/docs/zh/guides/get-started/tech-stack.mdx +1 -1
  41. package/docs/zh/guides/topic-detail/framework-plugin/introduction.mdx +61 -16
  42. package/package.json +7 -7
@@ -0,0 +1,236 @@
1
+ ---
2
+ sidebar_position: 2
3
+ title: Streaming SSR
4
+ ---
5
+
6
+ # Streaming SSR
7
+
8
+ ## Overview
9
+
10
+ Stream rendering is a new way of rendering, which can update the page content in real time when the user interacts with the page, thereby improving the user experience.
11
+
12
+ In traditional rendering, the rendering of the page is completed at once, while in stream rendering, the rendering of the page is gradually completed. When the user interacts with the page, data is loaded gradually instead of loading all at once.
13
+
14
+ Compared to traditional rendering:
15
+
16
+ - Faster perceived speed: Stream rendering can gradually display content during the rendering process to display the business home page at the fastest speed.
17
+ - Better user experience: Through stream rendering, users can see the content on the page faster, instead of waiting for the entire page to be rendered before they can interact.
18
+ - Better performance control: Stream rendering allows developers to better control the loading priority and order of pages, thereby optimizing performance and user experience.
19
+ - Better adaptability: Stream rendering can better adapt to different network speeds and device performances, allowing the page to perform better in various environments.
20
+
21
+ ## Usage
22
+
23
+ Modern.js supports streaming rendering in React 18 which can be enabled through the following configuration:
24
+
25
+ ```ts title="modern.config.ts"
26
+ import { defineConfig } from '@modern-js/app-tools';
27
+
28
+ export default defineConfig({
29
+ server: {
30
+ ssr: {
31
+ mode: 'stream',
32
+ },
33
+ },
34
+ });
35
+ ```
36
+
37
+ The streaming SSR of Modern.js is implemented based on React Router, and the main APIs involved are:
38
+
39
+ - [`defer`](https://reactrouter.com/en/main/utils/defer): This utility allows you to defer values returned from loaders by passing promises instead of resolved values.
40
+ - [`Await`](https://reactrouter.com/en/main/components/await): Used to render deferred values with automatic error handling.
41
+ - [`useAsyncValue`](https://reactrouter.com/en/main/hooks/use-async-value): Returns the resolved data from the nearest `<Await>` ancestor component.
42
+
43
+ ### Return async data
44
+
45
+ ```ts title="page.data.ts"
46
+ import { defer, type LoaderFunctionArgs } from '@modern-js/runtime/router';
47
+
48
+ interface User {
49
+ name: string;
50
+ age: number;
51
+ }
52
+
53
+ export interface Data {
54
+ data: User;
55
+ }
56
+
57
+ export const loader = ({ params }: LoaderFunctionArgs) => {
58
+ const userId = params.id;
59
+
60
+ const user = new Promise<User>(resolve => {
61
+ setTimeout(() => {
62
+ resolve({
63
+ name: `user-${userId}`,
64
+ age: 18,
65
+ });
66
+ }, 200);
67
+ });
68
+
69
+ return defer({ data: user });
70
+ };
71
+ ```
72
+
73
+ `user` is a `Promise` object that represents the data that needs to be obtained asynchronously. Use `defer` to handle the asynchronous retrieval of user. Note that `defer` must receive an object type parameter, so the parameter passed to `defer` is: `{ data: user }`.
74
+
75
+ `defer` can receive both asynchronous and synchronous data at the same time. For example:
76
+
77
+ ```ts title="page.data.ts"
78
+ // skip some codes
79
+
80
+ export default ({ params }: LoaderFunctionArgs) => {
81
+ const userId = params.id;
82
+
83
+ const user = new Promise<User>(resolve => {
84
+ setTimeout(() => {
85
+ resolve({
86
+ name: `user-${userId}`,
87
+ age: 18,
88
+ });
89
+ }, 200);
90
+ });
91
+
92
+ const otherData = new Promise<string>(resolve => {
93
+ setTimeout(() => {
94
+ resolve('some sync data');
95
+ }, 200);
96
+ });
97
+
98
+ return defer({
99
+ data: user,
100
+ other: await otherData,
101
+ });
102
+ };
103
+ ```
104
+
105
+ The data obtained from otherData is synchronous because it has an `await` keyword in front of it. It can be passed into `defer` together with the asynchronous data obtained from `user`.
106
+
107
+ ### Render asynchronous data.
108
+
109
+ With the `<Await>` component, you can retrieve the data asynchronously returned by the Data Loader and then render it. For example:
110
+
111
+ ```tsx title="page.tsx"
112
+ import { Await, useLoaderData } from '@modern-js/runtime/router';
113
+ import { Suspense } from 'react';
114
+ import type { Data } from './page.data';
115
+
116
+ const Page = () => {
117
+ const data = useLoaderData() as Data;
118
+
119
+ return (
120
+ <div>
121
+ User info:
122
+ <Suspense fallback={<div id="loading">loading user data ...</div>}>
123
+ <Await resolve={data.data}>
124
+ {user => {
125
+ return (
126
+ <div id="data">
127
+ name: {user.name}, age: {user.age}
128
+ </div>
129
+ );
130
+ }}
131
+ </Await>
132
+ </Suspense>
133
+ </div>
134
+ );
135
+ };
136
+
137
+ export default Page;
138
+ ```
139
+
140
+ `<Await>` needs to be wrapped inside the `<Suspense>` component. The `resolve` function passed into `<Await>` is used to asynchronously retrieve data from a Data Loader. Once the data has been retrieved, it is rendered using [Render Props](https://reactjs.org/docs/render-props.html) mode. During the data retrieval phase, the content specified in the `fallback` property of `<Suspense>` will be displayed.
141
+
142
+ :::warning Warning
143
+ When importing types from a Data Loader file, it is necessary to use the `import type` syntax to ensure that only type information is imported. This can avoid packaging Data Loader code into the bundle file of the front-end product.
144
+
145
+ Therefore, the import method here is: `import type { Data } from './page.data'`;
146
+ :::
147
+
148
+ You can also retrieve asynchronous data returned by the Data Loader using `useAsyncValue`. For example:
149
+
150
+ ```tsx title="page.tsx"
151
+ import { useAsyncValue } from '@modern-js/runtime/router';
152
+
153
+ // skip some codes
154
+
155
+ const UserInfo = () => {
156
+ const user = useAsyncValue();
157
+
158
+ return (
159
+ <div>
160
+ name: {user.name}, age: {user.age}
161
+ </div>
162
+ );
163
+ };
164
+
165
+ const Page = () => {
166
+ const data = useLoaderData() as Data;
167
+
168
+ return (
169
+ <div>
170
+ User info:
171
+ <Suspense fallback={<div id="loading">loading user data ...</div>}>
172
+ <Await resolve={data.data}>
173
+ <UserInfo />
174
+ </Await>
175
+ </Suspense>
176
+ </div>
177
+ );
178
+ };
179
+
180
+ export default Page;
181
+ ```
182
+
183
+ ### Error handling
184
+
185
+ The `errorElement` property of the `<Await>` component can be used to handle errors thrown when the Data Loader executes or when a child component renders.
186
+ For example, we intentionally throw an error in the Data Loader function:
187
+
188
+ ```ts title="page.data.ts"
189
+ import { defer } from '@modern-js/runtime/router';
190
+
191
+ export const loader = () => {
192
+ const data = new Promise((resolve, reject) => {
193
+ setTimeout(() => {
194
+ reject(new Error('error occurs'));
195
+ }, 200);
196
+ });
197
+
198
+ return defer({ data });
199
+ };
200
+ ```
201
+
202
+ Then use `useAsyncError` to get the error, and assign the component used to render the error to the `errorElement` property of the `<Await>` component:
203
+
204
+ ```tsx title="page.ts"
205
+ import { Await, useAsyncError, useLoaderData } from '@modern-js/runtime/router';
206
+ import { Suspense } from 'react';
207
+
208
+ export default function Page() {
209
+ const data = useLoaderData();
210
+
211
+ return (
212
+ <div>
213
+ Error page
214
+ <Suspense fallback={<div>loading ...</div>}>
215
+ <Await resolve={data.data} errorElement={<ErrorElement />}>
216
+ {(data: any) => {
217
+ return <div>never displayed</div>;
218
+ }}
219
+ </Await>
220
+ </Suspense>
221
+ </div>
222
+ );
223
+ }
224
+
225
+ function ErrorElement() {
226
+ const error = useAsyncError() as Error;
227
+ return <p>Something went wrong! {error.message}</p>;
228
+ }
229
+ ```
230
+
231
+ :::info More
232
+
233
+ 1. [Deferred Data](https://reactrouter.com/en/main/guides/deferred)
234
+ 2. [New Suspense SSR Architecture in React 18](https://github.com/reactwg/react-18/discussions/37)
235
+
236
+ :::
@@ -0,0 +1,341 @@
1
+ ---
2
+ sidebar_position: 1
3
+ title: Usage
4
+ ---
5
+
6
+ # Usage
7
+
8
+ Enabling SSR is simple. Just set the value of [`server.ssr`](/configure/app/server/ssr) to `true`.
9
+
10
+ ```ts title="modern.config.ts"
11
+ import { defineConfig } from '@modern-js/app-tools';
12
+
13
+ export default defineConfig({
14
+ server: {
15
+ ssr: true,
16
+ },
17
+ });
18
+ ```
19
+
20
+ ## SSR Data Fetch
21
+
22
+ Modern.js provides a Data Loader that simplifies data fetching for developers working with SSR and CSR. Each routing module, such as `layout.tsx` and `page.tsx`, can define its own Data Loader:
23
+
24
+ ```ts title="src/routes/page.data.ts"
25
+ export const loader = () => {
26
+ return {
27
+ message: 'Hello World',
28
+ };
29
+ };
30
+ ```
31
+
32
+ Within the component, data returned by the `loader` function can be accessed through the Hooks API:
33
+
34
+ ```tsx
35
+ export default () => {
36
+ const data = useLoaderData();
37
+ return <div>{data.message}</div>;
38
+ };
39
+ ```
40
+
41
+ Modern.js breaks the traditional model of server-side rendering (SSR) development and offers users a more user-friendly SSR development experience.
42
+
43
+ This feature offers elegant degradation processing. If the SSR request fails, it will automatically downgrade and restart the request on the browser side.
44
+
45
+ Developers should still be mindful of data fallback, including `null` values or unexpected data returns. This will help prevent React rendering errors and messy results during SSR.
46
+
47
+ :::info
48
+
49
+ 1. When requesting a page through client-side routing, Modern.js sends an HTTP request. The server receives the request and executes the corresponding Data Loader function for the page, then returns the execution result as a response to the browser.
50
+
51
+ 2. When using Data Loader, data is fetched before rendering. Modern.js also supports obtaining data during component rendering. For more related content, please refer to [Data Fetch](/guides/basic-features/data/data-fetch).
52
+
53
+ :::
54
+
55
+ ## Keep Rendering Consistent
56
+
57
+ In some businesses, it is usually necessary to make different UI displays based on the current operating container environment characteristics, such as [UA](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent) information.
58
+
59
+ If not handled carefully, unexpected rendering results are likely to occur.
60
+
61
+ Here is an example to show the problem when SSR and CSR rendering are inconsistent, add the following code to the component:
62
+
63
+ ```tsx
64
+ {
65
+ typeof window !== 'undefined' ? <div>browser content</div> : null;
66
+ }
67
+ ```
68
+
69
+ After launching the application and accessing the page, you will find that the browser console throws a warning message.
70
+
71
+ ```sh
72
+ Warning: Expected server HTML to contain a matching <div> in <div>.
73
+ ```
74
+
75
+ This is caused by React's hydration logic on the client side detecting inconsistencies between the rendered result and the SSR rendering result. Although the page appears normal, in complex applications, it is likely to cause problems such as DOM hierarchy confusion and style disorder.
76
+
77
+ :::info
78
+ More information about [`React hydrate`](https://reactjs.org/docs/react-dom.html#hydrate).
79
+
80
+ :::
81
+
82
+ The application needs to maintain consistency between SSR and CSR rendering results. If there is inconsistency, it means that this part of the content does not need to be rendered in SSR.
83
+
84
+ Modern.js provides a [`<NoSSR>`](/apis/app/runtime/core/use-runtime-context) component for such content that does not need to be rendered in SSR.
85
+
86
+ ```ts
87
+ import { NoSSR } from '@modern-js/runtime/ssr';
88
+ ```
89
+
90
+ Wrap the element that does not require SSR with the `NoSSR` component:
91
+
92
+ ```tsx
93
+ <NoSSR>
94
+ <div>client content</div>
95
+ </NoSSR>
96
+ ```
97
+
98
+ After modifying the code, refreshing the page shows that the previous warning has disappeared. Opening the Network tab of the browser devtools and checking the returned HTML document does not contain content wrapped by `NoSSR` components.
99
+
100
+ :::info
101
+ ['useRuntimeContext'](/apis/app/runtime/core/use-runtime-context) can get complete request information, which can be used to ensure consistent rendering results between SSR and CSR.
102
+
103
+ :::
104
+
105
+ ## Pay Attention to Memory Leaks
106
+
107
+ :::warning
108
+ Developers need to pay special attention to memory leaks in the SSR mode. Even tiny memory leaks can have an impact on the service after a large number of accesses.
109
+
110
+ :::
111
+
112
+ When using SSR, each request from the browser will trigger the server to re-execute the component rendering logic. Therefore, it is necessary to avoid defining any data structures that may continue to grow globally, subscribing to events globally, or creating streams that will not be destroyed globally.
113
+
114
+ For example, when using [redux-observable](https://redux-observable.js.org/), developers who are used to CSR development usually code in the component like this:
115
+
116
+ ```tsx
117
+ /* This code is for demonstration purposes only */
118
+ import { createEpicMiddleware, combineEpics } from 'redux-observable';
119
+
120
+ const epicMiddleware = createEpicMiddleware();
121
+ const rootEpic = combineEpics();
122
+
123
+ export default function Test() {
124
+ epicMiddleware.run(rootEpic);
125
+ return <div>Hello Modern.js</div>;
126
+ }
127
+ ```
128
+
129
+ Create a Middleware instance `epicMiddleware` outside the component and call epicMiddleware.run inside the component.
130
+
131
+ When running on the client-side, this code will not cause any issues. However, during SSR, the Middleware instance cannot be destroyed.
132
+
133
+ Every time a component is rendered and `epicMiddleware.run(rootEpic)` is called, new event bindings are added internally which causes the entire object to grow continuously and ultimately affects application performance.
134
+
135
+ CSR issues are not easy to detect, so when switching from CSR to SSR, if you are unsure whether the application has such problems, you can perform stress testing on applications.
136
+
137
+ ## Converging Server Data.
138
+
139
+ In order to maintain the data requested during the SSR phase, it can be directly used on the browser side. Modern.js will inject the data and state collected during rendering into HTML.
140
+
141
+ However, in CSR applications, there are often situations where interface data is large and component states are not converged. If SSR is used directly in this case, the rendered HTML may have a problem of being too large.
142
+
143
+ At this time, SSR may not only fail to improve user experience for applications but may also have an opposite effect.
144
+
145
+ Therefore, when using SSR, **developers need to properly slim down the application**.
146
+
147
+ 1. Focus on the first screen, SSR can request only the data needed for the first screen and render the remaining parts on the browser side.
148
+ 2. Remove data unrelated to rendering from the returned data of the interface.
149
+
150
+ ## Serverless Pre-render
151
+
152
+ :::warning
153
+ x.43.0+ has been deprecated, Please instance of [SSR Cache](guides/advanced-features/ssr/cache).
154
+ :::
155
+
156
+ Modern.js provides the Serverless Pre-rendering (SPR) feature to improve SSR performance.
157
+
158
+ SPR uses pre-rendering and caching technology to provide responsive performance for SSR pages. It enables SSR applications to have the response speed and stability of static web pages while also maintaining dynamic data updates.
159
+
160
+ Using SPR in Modern.js is very simple. Just add the PreRender component to your component, and the page where it is located will automatically enable SPR.
161
+
162
+ Here is a simulated component that uses the useLoaderData API. The request in the Data Loader takes 2 seconds to consume.
163
+
164
+ ```tsx title="page.data.ts"
165
+ import { useLoaderData } from '@modern-js/runtime/router';
166
+
167
+ export const loader = async () => {
168
+ await new Promise((resolve, reject) => {
169
+ setTimeout(() => {
170
+ resolve(null);
171
+ }, 2000);
172
+ });
173
+
174
+ return {
175
+ message: 'Hello Modern.js',
176
+ };
177
+ };
178
+ ```
179
+
180
+ ```tsx title="page.tsx"
181
+ import { useLoaderData } from '@modern-js/runtime/router';
182
+
183
+ export default () => {
184
+ const data = useLoaderData();
185
+ return <div>{data?.message}</div>;
186
+ };
187
+ ```
188
+
189
+ After executing the `dev` command and opening the page, it is obvious that the page needs to wait 2s before returning.
190
+
191
+ Use the `<PreRender>` component for optimization next, which can be directly exported from `@modern-js/runtime/ssr`.
192
+
193
+ ```ts
194
+ import { PreRender } from '@modern-js/runtime/ssr';
195
+ ```
196
+
197
+ Use the `<PreRender>` component within the routing component and set the parameter `interval` to indicate that the expiration time of this rendering result is 5 seconds:
198
+
199
+ ```tsx
200
+ <PreRender interval={5} />
201
+ ```
202
+
203
+ After modification, execute `pnpm run build && pnpm run serve` to start the application and open the page.
204
+
205
+ The first time it is opened, there is no difference in rendering compared to before, and there is still a 2-second delay.
206
+
207
+ Clicking refresh opens the page instantly, but at this point, the page data has not changed due to the refresh because the cache has not yet expired.
208
+
209
+ After waiting for 5 seconds and refreshing the page, the data on the page remained unchanged. After refreshing again, the data changed, but the response was nearly immediate.
210
+
211
+ This is because during the previous request, SPR had already asynchronously obtained a new rendering result in the background, and this time's requested page is a version that has been cached on the server.
212
+
213
+ One can imagine that when the `interval` is set to 1, users can have a responsive experience of static pages while perceiving real-time data.
214
+
215
+ :::info
216
+ For more detail, see [`<PreRender>`](/apis/app/runtime/ssr/pre-render).
217
+
218
+ :::
219
+
220
+ ## Treeshaking
221
+
222
+ When SSR is enabled, Modern.js uses the same entry point to build both SSR Bundle and CSR Bundle. Therefore, errors may occur if there are Web APIs in the SSR Bundle or Node APIs in the CSR Bundle.
223
+
224
+ Introducing Web APIs in components usually do some global listening or obtaining browser-related data, such as:
225
+
226
+ ```tsx
227
+ document.addEventListener('load', () => {
228
+ console.log('document load');
229
+ });
230
+ const App = () => {
231
+ return <div>Hello World</div>;
232
+ };
233
+ export default App;
234
+ ```
235
+
236
+ Importing Node API in component files is usually done when using `useLoader`, for example:
237
+
238
+ ```ts
239
+ import fse from 'fs-extra';
240
+ export default () => {
241
+ const file = fse.readFileSync('./myfile');
242
+ return {
243
+ ...
244
+ };
245
+ };
246
+ ```
247
+
248
+ ### Use Environment Variables
249
+
250
+ For the first case, we can directly use the built-in environment variable `MODERN_TARGET` in Modern.js to determine and remove unused code during build time:
251
+
252
+ ```ts
253
+ if (process.env.MODERN_TARGET === 'browser') {
254
+ document.addEventListener('load', () => {
255
+ console.log('document load');
256
+ });
257
+ }
258
+ ```
259
+
260
+ After the development environment is bundled, the SSR and CSR artifacts will be compiled into the following content. Therefore, there will be no more Web API errors in the SSR environment.
261
+
262
+ ```ts
263
+ // SSR production
264
+ if (false) {
265
+ }
266
+
267
+ // CSR production
268
+ if (true) {
269
+ document.addEventListener('load', () => {
270
+ console.log('document load');
271
+ });
272
+ }
273
+ ```
274
+
275
+ :::note
276
+ For more information, see [environment variables](/guides/basic-features/env-vars).
277
+
278
+ :::
279
+
280
+ ### Use File Suffix
281
+
282
+ But for example, in the second case, `fs-extra` is imported in the code, which has side effects using Node API internally. If it is directly referenced in the component, it will cause an error when CSR loading.
283
+
284
+ Environment variables does not work in this case. Modern.js also supports using files with the `.node.` suffix to distinguish between the packaging files of SSR Bundle and CSR Bundle products.
285
+
286
+ You can create a proxy layer by creating files with the same name but different extensions, such as `.ts` and `.node.ts`:
287
+
288
+ ```ts title="compat.ts"
289
+ export const readFileSync: any = () => {};
290
+ ```
291
+
292
+ ```ts title="compat.node.ts"
293
+ export { readFileSync } from 'fs-extra';
294
+ ```
295
+
296
+ Import `./compat` directly in the file. In SSR environment, files with `.node.ts` suffix will be used first, while in CSR environment, files with `.ts` suffix will be used.
297
+
298
+ ```ts title="App.tsx"
299
+ import { readFileSync } from './compat'
300
+
301
+ export const loader = () => {
302
+ const file = readFileSync('./myfile');
303
+ return {
304
+ ...
305
+ };
306
+ };
307
+ ```
308
+
309
+ ### Independent File
310
+
311
+ The two methods mentioned above will both bring some mental burden to developers. In real business scenarios, we found that most of the mixed Node/Web code appears in data requests.
312
+
313
+ Therefore, Modern.js has designed a [Data Fetch](/guides/basic-features/data/data-fetch) to separate CSR and SSR code based on [Nested Routing](/guides/basic-features/routes).
314
+
315
+ We can separate **data requests from component code** by using independent files. Write the component logic in `routes/page.tsx` and write the data request logic in `routes/page.data.ts`.
316
+
317
+ ```ts title="routes/page.tsx"
318
+ export default Page = () => {
319
+ return <div>Hello World<div>
320
+ }
321
+ ```
322
+
323
+ ```ts title="routes/page.data.tsx"
324
+ import fse from 'fs-extra';
325
+ export const loader = () => {
326
+ const file = fse.readFileSync('./myfile');
327
+ return {
328
+ ...
329
+ };
330
+ }
331
+ ```
332
+
333
+ ## Remote Request
334
+
335
+ When initiating interface requests in SSR, developers sometimes encapsulate isomorphic request tools themselves. For some interfaces that require passing user cookies, developers can use the ['useRuntimeContext'](/guides/basic-features/data/data-fetch#route-loader) API to get the request header for implementation.
336
+
337
+ It should be noted that the obtained request header is for HTML requests, which may not be suitable for API requests. Therefore, ** don't passed through all request headers **.
338
+
339
+ In addition, some backend interfaces or common gateways will verify based on the information in the request header. Full pass-through can easily lead to various difficult-to-troubleshoot issues, so it is recommended to **pass through as needed**.
340
+
341
+ If it is really necessary to pass through all request headers, please be sure to filter the `host` field.
@@ -4,9 +4,87 @@ sidebar_position: 4
4
4
 
5
5
  # Path Alias
6
6
 
7
- import Alias from '@modern-js/builder-doc/docs/en/shared/alias';
7
+ Path aliases allow developers to define aliases for modules, making it easier to reference them in code. This can be useful when you want to use a short, easy-to-remember name for a module instead of a long, complex path.
8
8
 
9
- <Alias />
9
+ For example, if you frequently reference the `src/common/request.ts` module in your project, you can define an alias for it as `@request` and then use `import request from '@request'` in your code instead of writing the full relative path every time. This also allows you to move the module to a different location without needing to update all the import statements in your code.
10
+
11
+ In Modern.js, there are two ways to set up path aliases:
12
+
13
+ - Through the `paths` configuration in `tsconfig.json`.
14
+ - Through the [source.alias](/configure/app/source/alias) configuration.
15
+
16
+ ## Using `tsconfig.json`'s `paths` Configuration
17
+
18
+ You can configure aliases through the `paths` configuration in `tsconfig.json`, which is the recommended approach in TypeScript projects as it also resolves the TS type issues related to path aliases.
19
+
20
+ For example:
21
+
22
+ ```json title="tsconfig.json"
23
+ {
24
+ "compilerOptions": {
25
+ "paths": {
26
+ "@common/*": ["./src/common/*"]
27
+ }
28
+ }
29
+ }
30
+ ```
31
+
32
+ After configuring, if you reference `@common/Foo.tsx` in your code, it will be mapped to the `<project>/src/common/Foo.tsx` path.
33
+
34
+ :::tip
35
+ You can refer to the [TypeScript - paths](https://www.typescriptlang.org/tsconfig#paths) documentation for more details.
36
+ :::
37
+
38
+ ## Use `source.alias` Configuration
39
+
40
+ Modern.js provides the [source.alias](/configure/app/source/alias) configuration option, which corresponds to the webpack/Rspack native [resolve.alias](https://webpack.js.org/configuration/resolve/#resolvealias) configuration. You can configure this option using an object or a function.
41
+
42
+ ### Use Cases
43
+
44
+ Since the `paths` configuration in `tsconfig.json` is written in a static JSON file, it lacks dynamism.
45
+
46
+ The `source.alias` configuration can address this limitation by allowing you to dynamically set the `source.alias` using JavaScript code, such as based on environment variables.
47
+
48
+ ### Object Usage
49
+
50
+ You can configure `source.alias` using an object, where the relative paths will be automatically resolved to absolute paths.
51
+
52
+ For example:
53
+
54
+ ```js
55
+ export default {
56
+ source: {
57
+ alias: {
58
+ '@common': './src/common',
59
+ },
60
+ },
61
+ };
62
+ ```
63
+
64
+ After configuring, if you reference `@common/Foo.tsx` in your code, it will be mapped to the `<project>/src/common/Foo.tsx` path.
65
+
66
+ ### Function Usage
67
+
68
+ You can also configure `source.alias` as a function, which receives the built-in `alias` object and allows you to modify it.
69
+
70
+ For example:
71
+
72
+ ```js
73
+ export default {
74
+ source: {
75
+ alias: alias => {
76
+ alias['@common'] = './src/common';
77
+ return alias;
78
+ },
79
+ },
80
+ };
81
+ ```
82
+
83
+ ### Priority
84
+
85
+ The `paths` configuration in `tsconfig.json` takes precedence over the `source.alias` configuration. When a path matches the rules defined in both `paths` and `source.alias`, the value defined in `paths` will be used.
86
+
87
+ You can adjust the priority of these two options using [source.aliasStrategy](/configure/app/source/alias-strategy).
10
88
 
11
89
  ## Default Aliases
12
90