Advertisement
Guest User

Untitled

a guest
Nov 17th, 2017
477
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React from 'react';
  2. import Helmet from 'react-helmet';
  3. import { renderToString } from 'react-dom/server';
  4. import { StaticRouter } from 'react-router-dom';
  5. import { renderRoutes } from 'react-router-config';
  6.  
  7. import express from 'express';
  8. import routes from './routes';
  9.  
  10. const isDev = process.env.NODE_ENV;
  11. const app = express();
  12.  
  13. if (isDev) {
  14.   const webpack = require('webpack');
  15.   const webpackDevMiddleware = require('webpack-dev-middleware');
  16.   const config = require('../../webpack.config.js');
  17.   const compiler = webpack(config);
  18.  
  19.   app.use(express.static('/public'));
  20.   app.use(
  21.     webpackDevMiddleware(compiler, {
  22.       publicPath: config.output.publicPath,
  23.       stats: 'errors-only',
  24.     })
  25.   );
  26. }
  27.  
  28. app.get('*', (req, res) => {
  29.   const helmet = Helmet.renderStatic();
  30.   const htmlAttrs = helmet.htmlAttributes.toComponent();
  31.   const bodyAttrs = helmet.bodyAttributes.toComponent();
  32.  
  33.   const context = {};
  34.   const data = {};
  35.  
  36.   res.set('content-type', 'text/html');
  37.  
  38.   res.send(
  39.     '<!DOCTYPE html>' +
  40.       renderToString(
  41.         <html {...htmlAttrs}>
  42.           <head>
  43.             {helmet.title.toComponent()}
  44.             {helmet.meta.toComponent()}
  45.             {helmet.link.toComponent()}
  46.           </head>
  47.           <body {...bodyAttrs}>
  48.             <div id="root">
  49.               <StaticRouter location={req.url} context={context}>
  50.                 {renderRoutes(routes)}
  51.               </StaticRouter>
  52.             </div>
  53.             <script
  54.               dangerouslySetInnerHTML={{
  55.                 __html: `window.__INITIAL_STATE__ = ${JSON.stringify(data)}`,
  56.               }}
  57.             />
  58.             <script src="/public/vendor.js" />
  59.             <script src="/public/app.js" />
  60.           </body>
  61.         </html>
  62.       )
  63.   );
  64. });
  65.  
  66. app.listen(3000, function() {
  67.   console.log('App listening on port 3000!'); // eslint-disable-line no-console
  68. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement