UNPKG

@platform/react.ssr

Version:

A lightweight SSR (server-side-rendering) system for react apps bundled with ParcelJS and hosted on S3.

57 lines (56 loc) 2.09 kB
import * as ReactDOMServer from 'react-dom/server'; import { constants, fs, jsYaml, time } from '../common'; import * as logger from './bundler.log'; const renderStatic = require('glamor/server').renderStatic; export async function prepare(args) { const { entries } = args; const bundleDir = fs.resolve(args.bundleDir); if (!(await fs.pathExists(bundleDir))) { throw new Error(`Cannot prepare, the directory does not exist. ${bundleDir}`); } const path = fs.join(bundleDir, constants.PATH.BUNDLE_MANIFEST); const manifest = await bundleManifest.write({ path, entries }); if (!args.silent) { logger.bundle({ bundleDir, manifest }); } return { bundleDir, manifest }; } const bundleManifest = { async create(args) { const dir = fs.dirname(args.path); const version = fs.basename(dir); const dirSize = await fs.size.dir(dir); const paths = await fs.glob.find(fs.join(dir, '**')); const files = paths.map((path) => { const size = dirSize.files.find((item) => item.path === path); const file = { path: path.substring(dir.length + 1), bytes: size ? size.bytes : -1, }; return file; }); const entries = (args.entries || []) .filter((entry) => files.some((file) => file.path === entry.file)) .map((entry) => renderEntry(entry)); const manifest = { version, createdAt: time.now.timestamp, bytes: dirSize.bytes, size: dirSize.toString(), files, entries, }; return manifest; }, async write(args) { const manifest = await bundleManifest.create(args); const yaml = jsYaml.safeDump(manifest); await fs.writeFile(args.path, yaml); return manifest; }, }; function renderEntry(args) { const { id = 'root', file, el } = args; const { html, css } = renderStatic(() => ReactDOMServer.renderToString(el)); return { file, id, html, css }; }