服务器端渲染

¥Server-Side Rendering

服务器端渲染(通常缩写为 "SSR")允许你将应用渲染为 HTML 字符串,该字符串可以发送到客户端以缩短加载时间。除此之外,还有其他场景(例如测试),SSR 被证明非常有用。

¥Server-Side Rendering (often abbreviated as "SSR") allows you to render your application to an HTML string that can be sent to the client to improve load time. Outside of that there are other scenarios, like testing, where SSR proves really useful.



安装

¥Installation

Preact 的服务器端渲染器位于 自己的存储库 中,可以通过你选择的打包程序安装:

¥The server-side renderer for Preact lives in its own repository and can be installed via your packager of choice:

npm install -S preact-render-to-string

上面的命令完成后,我们就可以立即开始使用了。

¥After the command above finished, we can start using it right away.

基本用法

¥Basic Usage

通过一个简单的代码片段可以最好地解释基本功能:

¥Basic functionality can be best explained via a simple snippet:

import render from 'preact-render-to-string';
import { h } from 'preact';

const name = 'Preact User!'
const App = <div class="foo">Hello {name}</div>;

console.log(render(App));
// <div class="foo">Hello Preact User!</div>

使用 Suspenselazy 进行异步渲染

¥Asynchronous Rendering with Suspense & lazy

你可能会发现需要渲染动态加载的组件,例如使用 Suspenselazy 来促进代码拆分(以及一些其他用例)。异步渲染器将等待 promise 的解决,允许你完全构造 HTML 字符串:

¥You may find that you need to render components that are dynamically loaded, like when using Suspense and lazy to facilitate code splitting (along with some other use cases). The async renderer will await the resolution of promises, allowing you to fully construct your HTML string:

// page/home.js
export default () => {
    return <h1>Home page</h1>;
};
// main.js
import { Suspense, lazy } from 'preact/compat';

// Creation of the lazy component
const HomePage = lazy(() => import('./pages/home'));

const Main = () => {
    return (
        <Suspense fallback={<p>Loading</p>}>
            <HomePage />
        </Suspense>
    );
};

以上是使用代码拆分的 Preact 应用的非常典型的设置,无需进行任何更改即可使用服务器端渲染。

¥The above is a very typical setup for a Preact application that uses code splitting, with no changes necessary to make use of server-side rendering.

为了渲染这一点,我们将稍微偏离基本使用示例并使用 renderToStringAsync 导出来渲染我们的应用:

¥To render this, we will deviate slightly from the basic usage example and use the renderToStringAsync export to render our application:

import { renderToStringAsync } from 'preact-render-to-string';
import { Main } from './main';

const main = async () => {
    // Rendering of lazy components
    const html = await renderToStringAsync(<Main />);

    console.log(html);
    // <h1>Home page</h1>
};

// Execution & error handling
main().catch((error) => {
    console.error(error);
});

浅层渲染

¥Shallow Rendering

出于某些目的,通常最好不要渲染整个树,而只渲染一层。为此,我们有一个浅渲染器,它将按名称打印子组件,而不是它们的返回值。

¥For some purposes it's often preferable to not render the whole tree, but only one level. For that we have a shallow renderer which will print child components by name, instead of their return value.

import { shallow } from 'preact-render-to-string';
import { h } from 'preact';

const Foo = () => <div>foo</div>;
const App = <div class="foo"><Foo /></div>;

console.log(shallow(App));
// <div class="foo"><Foo /></div>

漂亮模式

¥Pretty Mode

如果你需要以更人性化的方式获得渲染输出,我们可以满足你的需求!通过传递 pretty 选项,我们将保留空格并按预期缩进输出。

¥If you need to get the rendered output in a more human friendly way, we've got you covered! By passing the pretty option, we'll preserve whitespace and indent the output as expected.

import render from 'preact-render-to-string/jsx';
import { h } from 'preact';

const Foo = () => <div>foo</div>;
const App = <div class="foo"><Foo /></div>;

console.log(render(App, {}, { pretty: true }));
// Logs:
// <div class="foo">
//   <div>foo</div>
// </div>

JSX 模式

¥JSX Mode

如果你正在进行任何类型的快照测试,JSX 渲染模式尤其有用。它渲染输出,就好像它是用 JSX 编写的一样。

¥The JSX rendering mode is especially useful if you're doing any kind of snapshot testing. It renders the output as if it was written in JSX.

import render from 'preact-render-to-string/jsx';
import { h } from 'preact';

const App = <div data-foo={true} />;

console.log(render(App));
// Logs: <div data-foo={true} />
Preact 中文网 - 粤ICP备13048890号