Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add server rendering example #95

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 1 addition & 11 deletions examples/.babelrc
Original file line number Diff line number Diff line change
@@ -1,13 +1,3 @@
{
"stage": 0,
"plugins": [
"react-transform"
],
"extra": {
"react-transform": [{
"target": "react-transform-webpack-hmr",
"imports": ["react"],
"locals": ["module"]
}]
}
"stage": 0
}
2 changes: 1 addition & 1 deletion examples/basic/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
ReduxRouter,
routerStateReducer,
reduxReactRouter
} from 'redux-react-router';
} from 'redux-router';

import { Route, Link } from 'react-router';
import { Provider, connect } from 'react-redux';
Expand Down
2 changes: 1 addition & 1 deletion examples/basic/package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "redux-react-router-basic-example",
"name": "redux-router-basic-example",
"version": "0.1.0",
"description": "",
"main": "server.js",
Expand Down
6 changes: 4 additions & 2 deletions examples/package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "redux-react-router-examples",
"name": "redux-router-examples",
"version": "0.1.0",
"description": "",
"scripts": {
Expand All @@ -15,8 +15,10 @@
"babel-runtime": "^5.8.20",
"express": "^4.13.3",
"lodash": "^3.10.1",
"react-transform-webpack-hmr": "^0.1.4",
"query-string": "^2.4.1",
"react-transform-hmr": "^1.0.1",
"redux": "^2.0.0",
"serialize-javascript": "^1.1.2",
"webpack": "^1.12.1",
"webpack-dev-middleware": "^1.2.0",
"webpack-hot-middleware": "^2.0.0"
Expand Down
42 changes: 42 additions & 0 deletions examples/server-rendering/client.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, compose } from 'redux';

import {
ReduxRouter,
reduxReactRouter,
} from 'redux-router';

import { Provider } from 'react-redux';
import { devTools } from 'redux-devtools';
import { DevTools, DebugPanel, LogMonitor } from 'redux-devtools/lib/react';
import createHistory from 'history/lib/createBrowserHistory';

import routes from './routes';
import reducer from './reducer';
import {MOUNT_ID} from './constants';

const store = compose(
reduxReactRouter({ createHistory }),
devTools()
)(createStore)(reducer, window.__initialState);

const rootComponent = (
<Provider store={store}>
<ReduxRouter routes={routes} />
</Provider>
);

const mountNode = document.getElementById(MOUNT_ID);

// First render to match markup from server
ReactDOM.render(rootComponent, mountNode);
// Optional second render with dev-tools
ReactDOM.render((
<div>
{rootComponent}
<DebugPanel top right bottom>
<DevTools store={store} monitor={LogMonitor} />
</DebugPanel>
</div>
), mountNode);
56 changes: 56 additions & 0 deletions examples/server-rendering/components.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import React, { Component, PropTypes } from 'react';
import {connect} from 'react-redux';
import {Link} from 'react-router';

@connect(state => ({ routerState: state.router }))
export const App = class App extends Component {
static propTypes = {
children: PropTypes.node
}

render() {
const links = [
'/',
'/parent?foo=bar',
'/parent/child?bar=baz',
'/parent/child/123?baz=foo'
].map(l =>
<p>
<Link to={l}>{l}</Link>
</p>
);

return (
<div>
<h1>App Container</h1>
{links}
{this.props.children}
</div>
);
}
};

export const Parent = class Parent extends Component {
static propTypes = {
children: PropTypes.node
}

render() {
return (
<div>
<h2>Parent</h2>
{this.props.children}
</div>
);
}
};

export const Child = class Child extends Component {
render() {
return (
<div>
<h2>Child</h2>
</div>
);
}
};
1 change: 1 addition & 0 deletions examples/server-rendering/constants.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const MOUNT_ID = 'root';
13 changes: 13 additions & 0 deletions examples/server-rendering/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"name": "redux-router-server-rendering-example",
"version": "0.1.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node -r babel/register server.js"
},
"author": "Andrew Clark <[email protected]>",
"license": "MIT",
"dependencies": {}
}
6 changes: 6 additions & 0 deletions examples/server-rendering/reducer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import {combineReducers} from 'redux';
import {routerStateReducer} from '../../lib'; // 'redux-router';

export default combineReducers({
router: routerStateReducer
});
12 changes: 12 additions & 0 deletions examples/server-rendering/routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import React from 'react';
import {Route} from 'react-router';
import {App, Parent, Child} from './components';

export default (
<Route path="/" component={App}>
<Route path="parent" component={Parent}>
<Route path="child" component={Child} />
<Route path="child/:id" component={Child} />
</Route>
</Route>
);
80 changes: 80 additions & 0 deletions examples/server-rendering/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import express from 'express';
import webpack from 'webpack';
import React from 'react';
import {renderToString} from 'react-dom/server';
import {Provider} from 'react-redux';
import {createStore} from 'redux';
import {ReduxRouter} from '../../src'; // 'redux-router'
import {reduxReactRouter, match} from '../../src/server'; // 'redux-router/server';
import qs from 'query-string';
import serialize from 'serialize-javascript';

import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';

import config from './webpack.config.clientDev';
import {MOUNT_ID} from './constants';
import reducer from './reducer';
import routes from './routes';

const app = express();
const compiler = webpack(config);

const getMarkup = (store) => {
const initialState = serialize(store.getState());

const markup = renderToString(
<Provider store={store} key="provider">
<ReduxRouter/>
</Provider>
);

return `<!doctype html>
<html>
<head>
<title>Redux React Router – Server rendering Example</title>
</head>
<body>
<div id="${MOUNT_ID}">${markup}</div>
<script>window.__initialState = ${initialState};</script>
<script src="/static/bundle.js"></script>
</body>
</html>
`;
};

app.use(webpackDevMiddleware(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));

app.use(webpackHotMiddleware(compiler));

app.use((req, res) => {
const store = reduxReactRouter({ routes })(createStore)(reducer);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe use { routes, createHistory: createMemoryHistory } instead of { routes }?

const query = qs.stringify(req.query);
const url = req.path + (query.length ? '?' + query : '');

store.dispatch(match(url, (error, redirectLocation, routerState) => {
if (redirectLocation) {
res.redirect(redirectLocation.pathname + redirectLocation.search);
} else if (error) {
console.error('Router error:', error);
res.status(500);
res.send(error);
} else if (!routerState) {
res.status(500);
} else {
res.send(getMarkup(store));
}
}));
});

app.listen(3000, 'localhost', error => {
if (error) {
console.log(error);
return;
}

console.log('Listening at http://localhost:3000');
});
27 changes: 27 additions & 0 deletions examples/server-rendering/webpack.config.clientDev.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import {
HotModuleReplacementPlugin,
NoErrorsPlugin
} from 'webpack';

import baseConfig from '../webpack.config.base';
import mergeConfig from '../mergeConfig';
import path from 'path';

const clientDevConfig = mergeConfig(baseConfig, {
entry: [
'webpack-hot-middleware/client',
'./client'
],
output: {
path: path.resolve(__dirname, 'build'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new HotModuleReplacementPlugin(),
new NoErrorsPlugin()
],
devtool: 'eval'
});

export default clientDevConfig;
26 changes: 24 additions & 2 deletions examples/webpack.config.base.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,34 @@
import fs from 'fs';
import path from 'path';

const PROJECT_SRC = path.resolve(__dirname, '../src');

const babelrc = fs.readFileSync(path.join('..', '.babelrc'));
let babelLoaderQuery = {};

try {
babelLoaderQuery = JSON.parse(babelrc);
} catch (err) {
console.error('Error parsing .babelrc.');
console.error(err);
}
babelLoaderQuery.plugins = babelLoaderQuery.plugins || [];
babelLoaderQuery.plugins.push('react-transform');
babelLoaderQuery.extra = babelLoaderQuery.extra || {};
babelLoaderQuery.extra['react-transform'] = {
transforms: [{
transform: 'react-transform-hmr',
imports: ['react'],
locals: ['module']
}]
};

export default {
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel'],
loader: 'babel',
query: babelLoaderQuery,
exclude: path.resolve(__dirname, 'node_modules'),
include: [
path.resolve(__dirname),
Expand All @@ -16,7 +38,7 @@ export default {
},
resolve: {
alias: {
'redux-react-router': PROJECT_SRC
'redux-router': PROJECT_SRC
},
extensions: ['', '.js']
}
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
"react-dom": "^0.14.0-rc1",
"react-redux": "2.x",
"react-router": "1.0.0-rc1",
"react-transform-hmr": "^1.0.1",
"redux": "3.x",
"redux-devtools": "^2.1.0",
"rimraf": "^2.4.3",
Expand Down