客户端渲染(Client-Side Rendering,CSR)在浏览器端执行页面渲染。无法部署 Node.js 服务时,可在构建阶段生成静态 index.html 以实现纯客户端渲染。
以下场景推荐使用客户端渲染:
模板应包含资源注入与入口顺序:preload、css 在 head,importmap、moduleEntry、modulePreload 在 body。
import type { RenderContext } from '@esmx/core';
export default async (rc: RenderContext) => {
await rc.commit();
rc.html = `
<!DOCTYPE html>
<html>
<head>
${rc.preload()}
<title>Esmx</title>
${rc.css()}
</head>
<body>
<div id="app"></div>
${rc.importmap()}
${rc.moduleEntry()}
${rc.modulePreload()}
</body>
</html>
`;
};在构建阶段生成静态 HTML 文件,可通过 postBuild 钩子实现:
import type { EsmxOptions } from '@esmx/core';
export default {
async postBuild(esmx) {
const rc = await esmx.render();
esmx.writeSync(
esmx.resolvePath('dist/client', 'index.html'),
rc.html
);
}
} satisfies EsmxOptions;