Skip to content

サーバーサイドでの利用

サーバーサイドレンダリング (SSR)

EffCSS を使用すると、サーバーサイドでスタイルを適用できます。Style provider がクライアントサイド向けに初期設定をシリアライズするため、SSR または SSG に使用できます。

SSRの例

非常にシンプルです。Style Provider 自体がブラウザではないことを認識し、クライアントサイドと同じように動作します。レイアウトが完成したら、<head></head> に文字列化して追加するだけです。

React SSR の例はこちらです。

ts
import { StrictMode } from 'react';
import { renderToString } from 'react-dom/server';
import App from './App';
import { StyleProvider } from './styleContext.tsx';
import { useStyleProvider } from 'effcss';

export function render(_url: string) {
    // emulates Style provider methods and stores stylesheet makers
    const consumer = useStyleProvider();
    const html = renderToString(
        <StrictMode>
            <StyleProvider consumer={consumer}>
                <App />
            </StyleProvider>
        </StrictMode>
    );
    // consumer.toString returns HTML string with initial styles and
    // Style provider state
    const head = '' + consumer;
    return { html, head };
}
ts
import { StrictMode } from 'react';
import { hydrateRoot } from 'react-dom/client';
import App from './App';
import { StyleProvider } from './styleContext.tsx';
import { useStyleProvider } from 'effcss';

const consumer = useStyleProvider();

hydrateRoot(
    document.getElementById('root'),
    <StrictMode>
        <StyleProvider consumer={consumer}>
            <App />
        </StyleProvider>
    </StrictMode>
);

静的サイト生成(SSG)

useStyleProvidernoscript: trueを渡すだけで、文字列化された結果にはCSSスタイルのみが含まれます。

Apache License 2.0に基づいて公開されています。