How to use @loadable/server - 10 common examples

To help you get started, we’ve selected a few @loadable/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 jgeschwendt / serverless-react-ssr / src / platforms / lambda / render.ts View on Github external
export default async ({ location }) => {
  const { client, introspectionQueryResultData } = await LambdaContainerCache
  const statsFile = process.env.IS_OFFLINE
    ? resolve('.webpack/service/loadable-stats.json')
    : resolve('loadable-stats.json')

  const store = createStore(reducer)
  await client.resetStore() // the cache persists between lambda requests

  const extractor = new ChunkExtractor({ entrypoints: [], statsFile })

  const sheet = new ServerStyleSheet()

  const content = await renderToStringWithData(
    createElement(App, {
      client,
      extractor,
      location,
      routes,
      sheet: sheet.instance,
      store,
      theme
    })
  )

  const helmet = Helmet.renderStatic()
github frontity / frontity / packages / core / src / server / index.tsx View on Github external
Object.values(store.actions).map(({ beforeSSR }) => {
        if (beforeSSR) return beforeSSR();
      })
    );

    // Pass a context to HelmetProvider which will hold our state specific to each request.
    const helmetContext: HelmetContext = {};
    let materialCss = "";

    const Component = <App store={store} helmetContext={helmetContext} />;

    // If there's no client stats or there is no client entrypoint for the site we
    // want to load, we don't extract scripts.
    if (stats && hasEntryPoint({ stats, site: settings.name })) {
      // Run renderToString with ChunkExtractor to get the html.
      const extractor = new ChunkExtractor({
        stats,
        entrypoints: [settings.name]
      });
      const jsx = extractor.collectChunks(Component);

      const materialSheets = new ServerStyleSheets();
      html = renderToString(materialSheets.collect(jsx));
      materialCss = materialSheets.toString();

      // Get the linkTags. Crossorigin needed for type="module".
      const crossorigin = moduleStats && es5Stats ? { crossorigin: "" } : {};
      frontity.link = extractor.getLinkTags(crossorigin);

      // If we have both module and es5, do the type="module" dance:
      // https://jakearchibald.com/2017/es-modules-in-browsers/
      //
github smooth-code / smooth.js / packages / smooth / src / server / ssr.js View on Github external
return asyncHandler(async (req, res) => {
    const nodeStats = path.resolve(
      config.cachePath,
      'node/static/loadable-stats.json',
    )

    const webStats = path.resolve(
      config.cachePath,
      'web/static/loadable-stats.json',
    )

    const nodeExtractor = new ChunkExtractor({
      statsFile: nodeStats,
      outputPath: path.join(config.cachePath, 'node/static'),
    })

    const {
      Root,
      Html,
      ErrorContextProvider,
    } = nodeExtractor.requireEntrypoint()

    const webExtractor = new ChunkExtractor({ statsFile: webStats })
    const routerContext = {}
    const apolloClient = createApolloClient({
      schema,
      fragmentTypes,
      context: operation =>
github wix-incubator / rich-content / examples / main-ssr / src / server / index.js View on Github external
(req, res) => {
    const nodeExtractor = new ChunkExtractor({ statsFile: nodeStats });
    const { default: App } = nodeExtractor.requireEntrypoint();

    const webExtractor = new ChunkExtractor({ statsFile: webStats });
    const jsx = webExtractor.collectChunks(<App />);

    const html = renderToString(jsx);

    res.set('content-type', 'text/html');
    res.send(`<!DOCTYPE html>
    <html lang="en">
      <head>
        <title>Wix Rich Content SSR Example</title>
        <link href="https://fonts.googleapis.com/css?family=Roboto:300" rel="stylesheet" />
        ${webExtractor.getLinkTags()}
        ${webExtractor.getStyleTags()}
      </head>

      <body>
        <noscript>
github gregberge / loadable-components / examples / razzle / src / server.js View on Github external
.get('/*', (req, res) => {
    const extractor = new ChunkExtractor({
      statsFile: path.resolve('build/loadable-stats.json'),
      entrypoints: ['client'],
    })

    const html = renderToString(
      <ChunkExtractorManager extractor={extractor}>
        <ServerLocation url={req.url}>
          <App />
        </ServerLocation>
      </ChunkExtractorManager>,
    )

    res.status(200).send(
      oneLineTrim(htmlTemplate`
      <!doctype html>
      <html lang="">
github osamu38 / react-ssr-starter / src / server.js View on Github external
function getExtractor() {
  const statsFile = joinPath(!isDevelopment ? 'dist' : '', 'public/static/javascripts/loadable-stats.json');
  const extractor = new ChunkExtractor({ statsFile });

  return extractor;
}
github bitrecipe / mern-minimal / src / server / index.js View on Github external
return Promise.all(promises).then((data) => {

            let context = {};

            const statsFile = path.resolve(__dirname, "./../../dist/client/loadable-stats.json");

            const extractor = new ChunkExtractor({ statsFile, entrypoints: ["app"] });

            const jsx = extractor.collectChunks(
                <Provider store={store}>
                    <StaticRouter context={context} location={req.url}>
                        <App />
                    </StaticRouter>
                </Provider>
            );

            if (context.status === 404) {
                return res.status(404);
            }

            if (context.status === 302) {
                return res.redirect(302, context.url);
            }
github gregberge / loadable-components / examples / server-side-rendering / src / server / main.js View on Github external
(req, res) => {
    const nodeExtractor = new ChunkExtractor({ statsFile: nodeStats })
    const { default: App } = nodeExtractor.requireEntrypoint()

    const webExtractor = new ChunkExtractor({ statsFile: webStats })
    const jsx = webExtractor.collectChunks(<App />)

    const html = renderToString(jsx)

    res.set('content-type', 'text/html')
    res.send(`
      <!DOCTYPE html>
      <html>
        <head>
        ${webExtractor.getLinkTags()}
        ${webExtractor.getStyleTags()}
        </head>
        <body>
          <div id="main">${html}</div>
          ${webExtractor.getScriptTags()}
        </body>
github pluto-net / scinapse-web-client / server / ssr.tsx View on Github external
const ssr = async (req: Request | LambdaProxy.Event, version: string) => {
  const extractor = new ChunkExtractor({ statsFile });
  const fullURL = getFullUrl(req);

  const headers: { [key: string]: string | undefined } = {};
  for (const key of Object.keys(req.headers)) {
    const newKey = key.toLowerCase();
    if (newKey) {
      headers[newKey] = req.headers[key] as string;
    }
  }

  const axios = getAxiosInstance({
    headers: {
      cookie: headers.cookie,
      'user-agent': headers['user-agent'] || '',
      'x-forwarded-for': headers['x-forwarded-for'] || '',
      referer: headers.referer || '',
github smooth-code / smooth.js / packages / smooth / src / server / ssr.js View on Github external
config.cachePath,
      'web/static/loadable-stats.json',
    )

    const nodeExtractor = new ChunkExtractor({
      statsFile: nodeStats,
      outputPath: path.join(config.cachePath, 'node/static'),
    })

    const {
      Root,
      Html,
      ErrorContextProvider,
    } = nodeExtractor.requireEntrypoint()

    const webExtractor = new ChunkExtractor({ statsFile: webStats })
    const routerContext = {}
    const apolloClient = createApolloClient({
      schema,
      fragmentTypes,
      context: operation =>
        getContext({ req, config, operationContext: operation.getContext() }),
    })

    let jsx = (
      <ErrorContextProvider error={error}>
        <ApolloProvider client={apolloClient}>
          <StaticRouter location={req.url} context={routerContext}>
            <Root error={error} />
          </StaticRouter>
        </ApolloProvider>
      </ErrorContextProvider>

@loadable/server

Server utilities for loadable.

MIT
Latest version published 12 months ago

Package Health Score

86 / 100
Full package analysis

Popular @loadable/server functions