render.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /**
  2. * React Static Boilerplate
  3. * https://github.com/koistya/react-static-boilerplate
  4. * Copyright (c) Konstantin Tarkus (@koistya) | MIT license
  5. */
  6. import { join, dirname } from 'path';
  7. import React from 'react';
  8. import createTemplate from 'lodash/string/template';
  9. import fs from './lib/fs';
  10. const template = createTemplate(`<!doctype html>
  11. <html class="no-js" lang="">
  12. <head>
  13. <meta charset="utf-8">
  14. <meta http-equiv="x-ua-compatible" content="ie=edge">
  15. <title><%- title %></title>
  16. <meta name="description" content="">
  17. <meta name="viewport" content="width=device-width, initial-scale=1">
  18. <link rel="apple-touch-icon" href="apple-touch-icon.png">
  19. </head>
  20. <body>
  21. <div id="app"><%= body %></div>
  22. <script src="/app.js"></script>
  23. <script>
  24. (function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
  25. function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
  26. e=o.createElement(i);r=o.getElementsByTagName(i)[0];
  27. e.src='https://www.google-analytics.com/analytics.js';
  28. r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
  29. ga('create','UA-XXXXX-X','auto');ga('send','pageview');
  30. </script>
  31. </body>
  32. </html>`);
  33. async function render(page, component) {
  34. const data = {
  35. title: '',
  36. body: React.renderToString(component),
  37. };
  38. const file = join(__dirname, '../build', page.file.substr(0, page.file.lastIndexOf('.')) + '.html');
  39. const html = template(data);
  40. await fs.mkdir(dirname(file));
  41. await fs.writeFile(file, html);
  42. }
  43. export default async ({ pages }) => {
  44. console.log('render');
  45. const { route } = require('../build/app.node');
  46. for (const page of pages) {
  47. await route(page.path, render.bind(undefined, page));
  48. }
  49. };