|
| 1 | +console.time('Build html total') |
| 2 | + |
| 3 | +require('babel-register')() |
| 4 | + |
| 5 | +const fs = require('fs') |
| 6 | +const path = require('path') |
| 7 | +const mkdirp = require('mkdirp') |
| 8 | +const { createElement } = require('react') |
| 9 | +const { renderToStaticMarkup } = require('react-dom/server') |
| 10 | +const { ServerStyleSheet } = require('styled-components') |
| 11 | +const requireDirectory = require('require-directory') |
| 12 | + |
| 13 | +const srcDir = path.resolve(__dirname, '../pages') |
| 14 | +const outputDir = path.resolve(__dirname, '../docs') |
| 15 | +const Html = require('../components/Html.jsx').default |
| 16 | + |
| 17 | +function renderToHtml (srcPath) { |
| 18 | + const Component = require(srcPath).default |
| 19 | + const children = createElement(Component) |
| 20 | + const sheet = new ServerStyleSheet() |
| 21 | + // Uou have to render for sheet.CollectStyles to work, it seems. |
| 22 | + renderToStaticMarkup(sheet.collectStyles(createElement(Html, {children}))) |
| 23 | + const styleTags = sheet.getStyleElement() |
| 24 | + // Now render again with the style sheet |
| 25 | + const html = renderToStaticMarkup(createElement(Html, {children, styleTags})) |
| 26 | + return html |
| 27 | +} |
| 28 | + |
| 29 | +requireDirectory(module, '../pages', { |
| 30 | + include: /index.js$/, |
| 31 | + visit: (content, srcPath) => { |
| 32 | + const name = path.relative(srcDir, srcPath) |
| 33 | + console.time(`Build ${name}`) |
| 34 | + |
| 35 | + // Index.jsx => index.html |
| 36 | + // about/Index.jsx => index.html |
| 37 | + const outputFile = `${path.basename(srcPath, '.js')}.html`.toLowerCase() |
| 38 | + |
| 39 | + // /foo/bar/pages/Index.jsx => '' |
| 40 | + // /foo/bar/pages/about/Index.jsx => 'about' |
| 41 | + const relativePath = path.relative(srcDir, path.dirname(srcPath)) |
| 42 | + |
| 43 | + // '/foo/bar/docs', '', 'index.html' => '/foo/bar/docs/index.html' |
| 44 | + // '/foo/bar/docs', 'about', 'index.html' => '/foo/bar/docs/about/index.html' |
| 45 | + const outputPath = path.resolve(outputDir, relativePath, outputFile) |
| 46 | + |
| 47 | + const html = renderToHtml(srcPath) |
| 48 | + |
| 49 | + mkdirp.sync(path.dirname(outputPath)) |
| 50 | + |
| 51 | + fs.writeFileSync(outputPath, `<!doctype html>\n${html}`) |
| 52 | + |
| 53 | + console.timeEnd(`Build ${name}`) |
| 54 | + } |
| 55 | +}) |
| 56 | + |
| 57 | +console.timeEnd('Build html total') |
0 commit comments