Giter Site home page Giter Site logo

example-react-router-server-rendering-lazy-routes's Introduction

React Router Example: Server Rendering Lazy Routes

React Router has two great features that seem like they might not work well together: server side rendering and code splitting.

This minimal demo shows how to get the benefits of server rendering and partial app loading with lazy routes and webpack's code splitting.

Running

npm install
npm start
open http://localhost:5000

How it works

  1. Webpack's require.ensure defines code splitting points in the app.
  2. We polyfill require.ensure for node to just do a normal require.
  3. The server renders the app with match and the stateless <RoutingContext/>.
  4. When the client JavaScript loads, we use match to trigger the split code to load before rendering. If we didn't do that, then the first render would be null and not reuse the server rendered markup.
  5. We render on the client.
  6. We raise our arms in the air in triumph.

example-react-router-server-rendering-lazy-routes's People

Contributors

ryanflorence avatar taion avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

example-react-router-server-rendering-lazy-routes's Issues

Too dificult to understand !

this would have been the best example if this was written in express and simple js instead of es6.
i know es6 is cool but people are not fully comfortable with it :P ( like me ).

some lines written in es6 are just too difficult to understand. :( sorry im not genius

What if I wanted to have bundle per every single route

Because if I write it like this

export default {
  path: '/',
  component: App,
  indexRoute: {
    component: Bio
  },
  getChildRoutes(location, cb) {
    return [
      require.ensure([], (require) => cb(null, [require('./blog')])),
      require.ensure([], (require) => cb(null, [require('./contact')])),
      require.ensure([], (require) => cb(null, [require('./about')])),
    ]
  },
}

and I go for example to route /blog, all the extra 2 bundles with /contact and /about download.
And I want to download these only when they are clicked. What am I doing wrong? Should I nest that require.ensure calls?

Proper way to import assets

Hello,

I'm currently using this project as the basis for a personal project. I've got everything working well.
My question is how to properly process styles using this architecture. I'm attempting to process the files using scss with styles-loader, sass-loader, node-sass, and css-loader. When doing this it causes the component to load and then after 2 seconds the styles finally load. I then tried to process the scss outside of webpack but it changes the content type to from css to plain-text.

How do you go about processing your styles with an architecture like this?

Consider using babel-plugin-remove-webpack

I just published my first babel plugin, babel-plugin-remove-webpack. It automatically rewrites calls to require.ensure and require.include so the developer doesn't have to worry about them. A suggestion came up over at reddit that I talk with you guys about using it over here.

I'm open to your thoughts and suggestions.

After start, page shows, but can't find route /about

I see the page, app seems to have initialized fine, but when I click 'About', it gives:
main.js:1 Warning: Location "/about" did not match any routes
And nothing happens...
If I try to hit /about in the address bar manually, it says "Not Found"

Repo Question

Hello,

I'm currently working on moving my current codebase to use universal rendering and code-splits, as I was looking around this repo I have some questions:

  • Say I had more pages than the ones in this example, would webpack automatically generate more chunks incrementing the chunk [id] & [name]'s?
    I've read the Webpack Docs about Chunks but not sure whats going on here:
  output: {
    path: __dirname + '/dist',
    filename: '[name].js',
    chunkFilename: '[id].chunk.js',
    publicPath: '/dist/'
  },
  • adding any css from the createpage function in server-utils causes css to be rendered as text/javascript is there a way around this?

Does not work with Babel 6

I tried integrating the techniques here with my app that's using Babel 6. I kept getting 404's on child routes and I couldn't understand why. Finally, I updated all the dependencies on my clone of this repo to the latest versions to see if the problem was with my dependencies, and sure enough, it's giving me the same issues.

Here's what I updated the dependencies to:

"dependencies": {
    "babel-core": "^6.3.26",
    "babel-loader": "^6.2.0",
    "babel-preset-es2015": "^6.3.13",
    "babel-preset-react": "^6.3.13",
    "history": "^1.17.0",
    "react": "^0.14.3",
    "react-dom": "^0.14.3",
    "react-router": "^1.0.3",
    "webpack": "^1.12.9"
  }

and I have a .babelrc like this

{
  "presets": ["react", "es2015"]
}

Upon running npm start, everything is OK, console output is good. I navigate to localhost:5000, and the index page shows up. But if you click on "About", nothing happens, and if you visit localhost:5000/about directly you get a "Not Found" from the server.

I'm not 100% sure this is a Babel 6 issue or if potentially something else changed in the other libraries that's causing this.

Any idea what's going on?

how can I convert my routes and index.js so i use lazy load (newbie question)

I have looked at the example but can't seem to get it to work, At the moment my index.js looks like this, I don't have any server side rendering:

import React from 'react'
import ReactDOM from 'react-dom'
import getRoutes from './config/routes'
import { createStore, applyMiddleware, compose, combineReducers } from 'redux'
import { Provider } from 'react-redux'
import ReduxThunk from 'redux-thunk'
import * as reducers from 'redux/modules'
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'
import injectTapEventPlugin from 'react-tap-event-plugin'
import { routerReducer, syncHistoryWithStore, routerMiddleware, replace } from 'react-router-redux'
import { browserHistory } from 'react-router'

const historyMiddleware = routerMiddleware(browserHistory)

let reducer = combineReducers({...reducers, routing: routerReducer})
const store = createStore(
  reducer,
  compose(applyMiddleware(ReduxThunk, historyMiddleware),
   window.devToolsExtension ? window.devToolsExtension() : f => f))

const history = syncHistoryWithStore(browserHistory, store)

export function checkAuth () {
  console.log('Route onEnter CheckAuth function Ran')
  if (store.getState().users.isFetching === true) {
    return
  }
  const isAuthed = store.getState().users.isAuthed
  if (isAuthed === true) {
    if (store.getState().routing.locationBeforeTransitions.pathname === '/') {
      store.dispatch(replace('feed'))
      console.log('CheckAuth function changed the path to feed')
    } else {
      console.log('CheckAuth function ran & User is Authed but path is not /')
      return
    }
  } else {
    if (store.getState().routing.locationBeforeTransitions.pathname !== '/') {
      store.dispatch(replace('/'))
      console.log('CheckAuth function changed the path to /')
    }
  }
}

export function errorAuth () {
  if (store.getState().users.isFetching === true) {
    return
  }
  const isAuthed = store.getState().users.isAuthed

  if (isAuthed === true) {
    replace('/feed')
  } else {
    replace('/')
  }
}


const App = () => (
    <MuiThemeProvider>
      <Provider store = {store}>
        {getRoutes(checkAuth, history, errorAuth)}
      </Provider>
    </MuiThemeProvider>
    )

ReactDOM.render(
    <App/>,
  document.getElementById('app')
)

And my routes are declarative like this:

import React from 'react'
import { Router, Route, IndexRoute } from 'react-router'
import { MainContainer, HomeContainer, FeedContainer } from 'containers'
import {Error404} from 'components'

export default function getRoutes (checkAuth, history, errorAuth) {
  return (
      <Router history={history}>
        <Route path='/' component={MainContainer}>
          <IndexRoute component = {HomeContainer} onEnter = {checkAuth}/>
          <Route path='feed' component = {FeedContainer} onEnter = {checkAuth}/>
          <Route path='*' component = {Error404} />
        </Route>
      </Router>
  )
}

update to latest react-router (2.0.0-rc4 as of writing)

Update react-router
npm install react-router@beta

npm start throws an error
Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

Also thank you for react-router!

After start, page shows, but can't find route /about

I see the page, app seems to have initialized fine, but when I click 'About', it gives:
main.js:1 Warning: Location "/about" did not match any routes
And nothing happens...
If I try to hit /about in the address bar manually, it says "Not Found"

wouldnt be able to start here is the log.

0 info it worked if it ends with ok
1 verbose cli [ 'B:\node\node.exe',
1 verbose cli 'B:\node\node_modules\npm\bin\npm-cli.js',
1 verbose cli 'start' ]
2 info using [email protected]
3 info using [email protected]
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info prestart [email protected]
6 info start [email protected]
7 verbose unsafe-perm in lifecycle true
8 info [email protected] Failed to exec start script
9 verbose stack Error: [email protected] start: NODE_ENV=production webpack --progress && babel-node modules/server.js
9 verbose stack Exit status 1
9 verbose stack at EventEmitter. (B:\node\node_modules\npm\lib\utils\lifecycle.js:217:16)
9 verbose stack at emitTwo (events.js:87:13)
9 verbose stack at EventEmitter.emit (events.js:172:7)
9 verbose stack at ChildProcess. (B:\node\node_modules\npm\lib\utils\spawn.js:24:14)
9 verbose stack at emitTwo (events.js:87:13)
9 verbose stack at ChildProcess.emit (events.js:172:7)
9 verbose stack at maybeClose (internal/child_process.js:827:16)
9 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5)
10 verbose pkgid [email protected]
11 verbose cwd B:\example-react-router-server-rendering-lazy-routes-master
12 error Windows_NT 10.0.10586
13 error argv "B:\node\node.exe" "B:\node\node_modules\npm\bin\npm-cli.js" "start"
14 error node v4.4.5
15 error npm v2.15.5
16 error code ELIFECYCLE
17 error [email protected] start: NODE_ENV=production webpack --progress && babel-node modules/server.js
17 error Exit status 1
18 error Failed at the [email protected] start script 'NODE_ENV=production webpack --progress && babel-node modules/server.js'.
18 error This is most likely a problem with the react-router-lazy-route-server-rendering package,
18 error not with npm itself.
18 error Tell the author that this fails on your system:
18 error NODE_ENV=production webpack --progress && babel-node modules/server.js
18 error You can get information on how to open an issue for this project with:
18 error npm bugs react-router-lazy-route-server-rendering
18 error Or if that isn't available, you can get their info via:
18 error
18 error npm owner ls react-router-lazy-route-server-rendering
18 error There is likely additional logging output above.
19 verbose exit [ 1, true ]

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.