|
| 1 | +/*eslint-disable no-console */ |
| 2 | +import express from 'express' |
| 3 | +import serialize from 'serialize-javascript' |
| 4 | + |
| 5 | +import webpack from 'webpack' |
| 6 | +import webpackDevMiddleware from 'webpack-dev-middleware' |
| 7 | +import webpackConfig from './webpack.config' |
| 8 | + |
| 9 | +import React from 'react' |
| 10 | +import { renderToString } from 'react-dom/server' |
| 11 | +import { Provider } from 'react-redux' |
| 12 | +import { createMemoryHistory, match, RouterContext } from 'react-router' |
| 13 | +import { syncHistoryWithStore } from '../../src' |
| 14 | + |
| 15 | +import { configureStore } from './store' |
| 16 | +import routes from './routes' |
| 17 | + |
| 18 | +const app = express() |
| 19 | + |
| 20 | +app.use(webpackDevMiddleware(webpack(webpackConfig), { |
| 21 | + publicPath: '/__build__/', |
| 22 | + stats: { |
| 23 | + colors: true |
| 24 | + } |
| 25 | +})) |
| 26 | + |
| 27 | +const HTML = ({ content, store }) => ( |
| 28 | + <html> |
| 29 | + <body> |
| 30 | + <div id="root" dangerouslySetInnerHTML={{ __html: content }}/> |
| 31 | + <div id="devtools"/> |
| 32 | + <script dangerouslySetInnerHTML={{ __html: `window.__initialState__=${serialize(store.getState())};` }}/> |
| 33 | + <script src="/__build__/bundle.js"/> |
| 34 | + </body> |
| 35 | + </html> |
| 36 | +) |
| 37 | + |
| 38 | +app.use(function (req, res) { |
| 39 | + const memoryHistory = createMemoryHistory(req.path) |
| 40 | + const store = configureStore(memoryHistory) |
| 41 | + const history = syncHistoryWithStore(memoryHistory, store) |
| 42 | + |
| 43 | + match({ history, routes, location: req.url }, (error, redirectLocation, renderProps) => { |
| 44 | + if (error) { |
| 45 | + res.status(500).send(error.message) |
| 46 | + } else if (redirectLocation) { |
| 47 | + res.redirect(302, redirectLocation.pathname + redirectLocation.search) |
| 48 | + } else if (renderProps) { |
| 49 | + const content = renderToString( |
| 50 | + <Provider store={store}> |
| 51 | + <RouterContext {...renderProps}/> |
| 52 | + </Provider> |
| 53 | + ) |
| 54 | + |
| 55 | + res.send('<!doctype html>\n' + renderToString(<HTML content={content} store={store}/>)) |
| 56 | + } |
| 57 | + }) |
| 58 | +}) |
| 59 | + |
| 60 | +app.listen(8080, function () { |
| 61 | + console.log('Server listening on http://localhost:8080, Ctrl+C to stop') |
| 62 | +}) |
0 commit comments