Skip to content

Commit cfc5bda

Browse files
authored
feat(app-tools): SSR mode support async entry (#3735)
* chore: ssr mode support async entry * chore: add chinese changest * chore: update changeset * chore: use constant and change variable name * chore: use Promise.resolve to resolve async entry
1 parent 4cbe958 commit cfc5bda

File tree

3 files changed

+33
-2
lines changed

3 files changed

+33
-2
lines changed

.changeset/chilly-ducks-perform.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'@modern-js/app-tools': patch
3+
'@modern-js/prod-server': patch
4+
---
5+
6+
feat: ssr mode support async entry
7+
feat: ssr 模式支持异步入口

packages/server/prod-server/src/libs/render/ssr.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,8 @@ export const render = async (
8181
context.metrics = createMetrics(context, ctx.metrics);
8282

8383
runner.extendSSRContext(context);
84-
const serverRender = require(bundleJS)[SERVER_RENDER_FUNCTION_NAME];
84+
const bundleJSContent = await Promise.resolve(require(bundleJS));
85+
const serverRender = bundleJSContent[SERVER_RENDER_FUNCTION_NAME];
8586
const content = await cache(serverRender, ctx)(context);
8687

8788
const { url, status = 302 } = context.redirection;

packages/solutions/app-tools/src/analyze/generateCode.ts

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
isSSGEntry,
77
isUseSSRBundle,
88
logger,
9+
SERVER_RENDER_FUNCTION_NAME,
910
} from '@modern-js/utils';
1011
import { IAppContext, PluginAPI } from '@modern-js/core';
1112
import type {
@@ -285,9 +286,31 @@ export const generateCode = async (
285286

286287
// generate entry file.
287288
if (config.source.enableAsyncEntry) {
289+
let rawAsyncEntryCode = `import('./${ENTRY_BOOTSTRAP_FILE_NAME}');`;
290+
const ssr = getEntryOptions(
291+
entryName,
292+
config.server.ssr,
293+
config.server.ssrByEntries,
294+
packageName,
295+
);
296+
if (ssr) {
297+
rawAsyncEntryCode = `
298+
export const ${SERVER_RENDER_FUNCTION_NAME} = async (...args) => {
299+
let entry = await ${rawAsyncEntryCode};
300+
if (entry.default instanceof Promise){
301+
entry = await entry.default;
302+
return entry.default.${SERVER_RENDER_FUNCTION_NAME}.apply(null, args);
303+
}
304+
return entry.${SERVER_RENDER_FUNCTION_NAME}.apply(null, args);
305+
};
306+
if(typeof window!=='undefined'){
307+
${rawAsyncEntryCode}
308+
}
309+
`;
310+
}
288311
const { code: asyncEntryCode } = await hookRunners.modifyAsyncEntry({
289312
entrypoint,
290-
code: `import('./${ENTRY_BOOTSTRAP_FILE_NAME}');`,
313+
code: rawAsyncEntryCode,
291314
});
292315
fs.outputFileSync(entryFile, asyncEntryCode, 'utf8');
293316

0 commit comments

Comments
 (0)