UNPKG

@platform/react.ssr

Version:

An SSR (server-side-render) system for react apps bundled with ParcelJS and hosted on S3.

50 lines (49 loc) 1.82 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 size = await fs.size.dir(dir); let files = await fs.glob.find(fs.join(dir, '**')); files = files.map(path => path.substring(dir.length + 1)); const entries = (args.entries || []) .filter(entry => files.includes(entry.file)) .map(entry => renderEntry(entry)); const manifest = { version, createdAt: time.now.timestamp, bytes: size.bytes, size: size.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 } = args; const { html, css } = renderStatic(() => ReactDOMServer.renderToString(args.el)); return { file, id, html, css }; }