Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React from 'react';
- import Helmet from 'react-helmet';
- import { renderToString } from 'react-dom/server';
- import { StaticRouter } from 'react-router-dom';
- import { renderRoutes } from 'react-router-config';
- import express from 'express';
- import routes from './routes';
- const isDev = process.env.NODE_ENV;
- const app = express();
- if (isDev) {
- const webpack = require('webpack');
- const webpackDevMiddleware = require('webpack-dev-middleware');
- const config = require('../../webpack.config.js');
- const compiler = webpack(config);
- app.use(express.static('/public'));
- app.use(
- webpackDevMiddleware(compiler, {
- publicPath: config.output.publicPath,
- stats: 'errors-only',
- })
- );
- }
- app.get('*', (req, res) => {
- const helmet = Helmet.renderStatic();
- const htmlAttrs = helmet.htmlAttributes.toComponent();
- const bodyAttrs = helmet.bodyAttributes.toComponent();
- const context = {};
- const data = {};
- res.set('content-type', 'text/html');
- res.send(
- '<!DOCTYPE html>' +
- renderToString(
- <html {...htmlAttrs}>
- <head>
- {helmet.title.toComponent()}
- {helmet.meta.toComponent()}
- {helmet.link.toComponent()}
- </head>
- <body {...bodyAttrs}>
- <div id="root">
- <StaticRouter location={req.url} context={context}>
- {renderRoutes(routes)}
- </StaticRouter>
- </div>
- <script
- dangerouslySetInnerHTML={{
- __html: `window.__INITIAL_STATE__ = ${JSON.stringify(data)}`,
- }}
- />
- <script src="/public/vendor.js" />
- <script src="/public/app.js" />
- </body>
- </html>
- )
- );
- });
- app.listen(3000, function() {
- console.log('App listening on port 3000!'); // eslint-disable-line no-console
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement