Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
// $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())
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(
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>
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(() => (
render(app)
))
html = res.html
css = `<style>${res.css}</style>`
return { path, html, css, props }
default:
html = render(app)
return { path, html, props }
}
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;
}
}
};
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);
caches.reduce((prev, next) => next === prev, true) &&
(await checkCache("config.yml", JSON.stringify(config)))
) {
return true;
}
const messages = await i18n();
try {
const links = articles.map(article => formatURL(article.path));
const metadatas = articles.map(article => ({
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");
}
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");
}
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', () => {
res.write(after);
res.end();
});
}
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);
};