How to use emotion-server - 10 common examples

To help you get started, we’ve selected a few emotion-server examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github emotion-js / emotion / packages / emotion-server / types / tests.tsx View on Github external
// $ExpectError
extractCritical(renderedString, undefined as any)

// $ExpectType string
renderStylesToString(renderedString)
// $ExpectError
renderStylesToString()
// $ExpectError
renderStylesToString(renderedString, undefined as any)

// $ExpectType ReadWriteStream
renderStylesToNodeStream()
// $ExpectError
renderStylesToNodeStream(undefined as any)

renderedNodeStream.pipe(renderStylesToNodeStream())
github wp-pwa / wp-pwa / core / pwa / server / index.js View on Github external
packages: activatedPackages,
      }),
    );
    store.dispatch(settingsModule.actions.settingsUpdated({ settings }));

    // Run and wait until all the server sagas have run.
    const startSagas = new Date();
    const sagaPromises = Object.values(serverSagas).map(saga => store.runSaga(saga).done);
    store.dispatch(buildModule.actions.serverSagasInitialized());
    await Promise.all(sagaPromises);
    store.dispatch(buildModule.actions.serverFinished({ timeToRunSagas: new Date() - startSagas }));

    // Generate React SSR.
    app = renderToString();

    const { html, ids, css } = extractCritical(app);

    // Get static helmet strings.
    const helmet = Helmet.renderStatic();

    // Flush chunk names and extract scripts, css and css<->scripts object.
    const chunkNames = flushChunkNames();
    const { cssHashRaw, scripts, stylesheets } = flushChunks(clientStats, { chunkNames });

    const publicPath = req.query.static
      ? `${req.query.static.replace(/\/$/g, '')}/static/`
      : '/static/';
    const cssHash = JSON.stringify(mapValues(cssHashRaw, cssPath => `${publicPath}${cssPath}`));
    const scriptsWithoutBootstrap = scripts.filter(script => !/bootstrap/.test(script));
    const chunksForArray = scriptsWithoutBootstrap.map(script => `'${script}'`).join(',');
    const bootstrapFileName = scripts.filter(script => /bootstrap/.test(script));
    const bootstrapString = await readFile(
github gatsbyjs / gatsby / packages / gatsby-plugin-emotion / src / gatsby-ssr.js View on Github external
export const replaceRenderer = ({
  bodyComponent,
  replaceBodyHTMLString,
  setHeadComponents,
}) => {
  const { html, ids, css } = extractCritical(
    renderToString(wrapElement(bodyComponent))
  )

  setHeadComponents([
    // eslint-disable-next-line react/jsx-key
    <style data-emotion-css="{ids.join(`">,
  ])

  replaceBodyHTMLString(html)
}
</style>
github c8r / x0 / lib / build.js View on Github external
let html
  let css
  switch (cssLibrary) {
    case 'styled-components':
      const { ServerStyleSheet } = require('styled-components')
      const sheet = new ServerStyleSheet()
      html = render(
        sheet.collectStyles(
          React.createElement(App.default, { routes, path })
        )
      )
      css = sheet.getStyleTags()
      return { path, html, css, props }
    case 'emotion':
      const { renderStylesToString } = require('emotion-server')
      html = renderStylesToString(
        render(app)
      )
      return { path, html, props }
    case 'glamor':
      // doesn't seem to be working...
      const glamor = require('glamor/server')
      const res = glamor.renderStatic(() =&gt; (
        render(app)
      ))
      html = res.html
      css = `<style>${res.css}</style>`
      return { path, html, css, props }
    default:
      html = render(app)
      return { path, html, props }
  }
github gourmetjs / gourmet-ssr / contrib / emotion-renderer / gmsrc / getEmotionServerRenderer.js View on Github external
renderToMedium(gmctx, element) {
      element = super.renderToMedium(gmctx, element);

      if (element) {
        if (typeof element === "string") {
          return renderStylesToString(element);
        } else {
          const output = renderStylesToNodeStream();
          return pump(element, output, err => {
            // `pump` doesn't forward the error from source to output stream
            // (perhaps) per Node's default behavior. It just silently destroys
            // the output stream to make sure no leak occurs.
            if (err)
              output.destroy(err);
          });
        }
      } else {
        return element;
      }
    }
  };
github SubstraFoundation / substra-frontend / src / server / render.js View on Github external
const renderStreamed = async (ctx, path, clientStats, outputPath) => {
    // Grab the CSS from our sheetsRegistry.
    clearChunks();

    const store = await configureStore(ctx);

    if (!store) return; // no store means redirect was already served
    const stateJson = JSON.stringify(store.getState());

    const {css} = flushChunks(clientStats, {outputPath});

    const chunkNames = [];
    const app = createApp(App, store, chunkNames);

    const stream = renderToNodeStream(app).pipe(renderStylesToNodeStream());

    // flush the head with css & js resource tags first so the download starts immediately
    const early = earlyChunk(css, stateJson);


    // DO not use redis cache on dev
    let mainStream;
    if (process.env.NODE_ENV === 'development') {
        mainStream = ctx.body;
    }
    else {
        mainStream = createCacheStream(path);
        mainStream.pipe(ctx.body);
    }

    mainStream.write(early);
github contentz-tech / contentz / src / lib / render-archive.js View on Github external
caches.reduce((prev, next) =&gt; next === prev, true) &amp;&amp;
    (await checkCache("config.yml", JSON.stringify(config)))
  ) {
    return true;
  }

  const messages = await i18n();

  try {
    const links = articles.map(article =&gt; formatURL(article.path));
    const metadatas = articles.map(article =&gt; ({
      path: article.path,
      ...getMeta(article).data
    }));

    const html = renderStylesToString(
      ReactDOMServer.renderToStaticMarkup(
        jsx(
          IntlProvider,
          { locale: config.language || config.lang || "en", messages },
          jsx(
            Document,
            { config, links, path: "./articles.mdx" },
            jsx(ArchivePage, { config, articles: metadatas })
          )
        )
      )
    );
    await writeContent(`${html}`);
  } finally {
    console.log("Render completed: Archive");
  }
github contentz-tech / contentz / src / lib / render-home.js View on Github external
async function render(config) {
  if (await checkCache("config.yml", JSON.stringify(config))) return true;
  const messages = await i18n();
  try {
    const html = renderStylesToString(
      ReactDOMServer.renderToStaticMarkup(
        jsx(
          IntlProvider,
          { locale: config.language || config.lang || "en", messages },
          jsx(
            Document,
            { config, messages, path: "home.mdx" },
            jsx(HomePage, { config, messages })
          )
        )
      )
    );
    await writeContent(`${html}`);
  } finally {
    console.log("Render completed: Home");
  }
github lskjs / lskjs / packages / reactapp / src / ReactApp.server.js View on Github external
async renderToNodeStream({ res, render, component }) {
    const delemitter = ``;
    const content = await render(delemitter);
    const [before, after] = content.split(delemitter);
    res.write(before);
    const stream = renderToNodeStream(component).pipe(renderStylesToNodeStream());
    stream.pipe(res, { end: false });
    stream.on('end', () =&gt; {
      res.write(after);
      res.end();
    });
  }
github staylor / graphql-wordpress / packages / draft / src / server / router / serve.js View on Github external
console.log(e);
  }

  const state = client.cache.extract();

  const [header, footer] = template({
    helmet: res.locals.helmetContext.helmet,
    stylesheets,
    state,
    assets,
  });

  res.status(200);
  res.write(header);
  renderToNodeStream(app)
    .pipe(renderStylesToNodeStream())
    .pipe(
      through(
        function write(data) {
          this.queue(data);
        },
        function end() {
          this.queue(footer);
          this.queue(null);
        }
      )
    )
    .pipe(res);
};

emotion-server

Extract and inline critical css with emotion for server side rendering.

MIT
Latest version published 3 years ago

Package Health Score

78 / 100
Full package analysis