Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Jan 22, 2020. It is now read-only.
/react-enginePublic archive

a composite render engine for universal (isomorphic) express apps to render both plain react views and react-router views

License

NotificationsYou must be signed in to change notification settings

paypal/react-engine

Repository files navigation

Build Status

What is react-engine?

  • a react render engine forUniversal (previouslyIsomorphic) JavaScript apps written with express
  • renders both plain react views andoptionally react-router views
  • enables server rendered views to be client mountable

Install

# In your express app, react-engine needs to be installed alongside react/react-dom (react-router is optional)$ npm install react-engine react react-dom react-router --save

Usage On Server Side

Setup in an Express app
varExpress=require('express');varReactEngine=require('react-engine');varapp=Express();// create an engine instancevarengine=ReactEngine.server.create({/*    see the complete server options spec here:    https://github.com/paypal/react-engine#server-options-spec  */});// set the engineapp.engine('.jsx',engine);// set the view directoryapp.set('views',__dirname+'/views');// set jsx or js as the view engine// (without this you would need to supply the extension to res.render())// ex: res.render('index.jsx') instead of just res.render('index').app.set('view engine','jsx');// finally, set the custom viewapp.set('view',require('react-engine/lib/expressView'));
Setup in aKrakenJS app's config.json
{"express": {"view engine":"jsx","view":"require:react-engine/lib/expressView",  },"view engines": {"jsx": {"module":"react-engine/lib/server","renderer": {"method":"create","arguments": [{/*see the complete server options spec here:https://github.com/paypal/react-engine#server-options-spec*/        }]      }    }  }}
Server options spec

Pass in a JavaScript object as options to the react-engine'sserver engine create method.The options object should contain the mandatoryroutes property with the route definition.

Additionally, it can contain the followingoptional properties,

  • docType: <String> - a string that can be used as a doctype (Default:<!DOCTYPE html>).(docType might not make sense if you are rendering partials/sub page components, in that case you can pass an empty string as docType)

  • routesFilePath: <String> - path for the file that contains the react router routes.react-engine uses this behind the scenes to reload the routes file incases whereexpress's app propertyview cache is false, this way you don't need to restart the server every time a change is made in the view files or routes file.

  • renderOptionsKeysToFilter: <Array> - an array of keys that need to be filtered out from the data object that gets fed into the react component for rendering.more info

  • performanceCollector: <Function> - to collectsperf stats

  • scriptLocation: <String> - where in the HTML you want the client data (i.e.<script>var __REACT_ENGINE__ = ... </script>) to be appended (Default:body).If the value is undefined or set tobody the script is placed before the</body> tag.The only other value ishead which appends the script before the</head> tag.

  • staticMarkup: <Boolean> - a boolean that indicates if render components without React data attributes and client data. (Default:false). This is useful if you want to render simple static page, as stripping away the extra React attributes and client data can save lots of bytes.

  • scriptType: <String> - a string that can be used as the type for the script (if it is included, which is only if staticMarkup is false). (Default:application/json).

Rendering views on server side
vardata={};// your data model// for a simple react view renderingres.render(viewName,data);// for react-router rendering// pass in the `url` and react-engine// will run the react-router behind the scenes.res.render(req.url,data);

Usage On Client Side (Mounting)

// assuming we use a module bundler like `webpack` or `browserify`varclient=require('react-engine/lib/client');// finally, boot whenever your app is ready// example:document.addEventListener('DOMContentLoaded',functiononLoad(){// `onBoot` - Function (optional)// returns data that was used// during rendering as the first argument// the second argument is the `history` object that was created behind the scenes// (only available while using react-router)client.boot(/* client options object */,functiononBoot(data,history){});};// if the data is needed before booting on// client, call `data` function anytime to get it.// example:vardata=client.data();
Client options spec

Pass in a JavaScript object as options to the react-engine's client boot function.It can contain the following properties,

  • routes :required -Object - the route definition file.
  • viewResolver :required -Function - a function that react-engine needs to resolve the view file.an example of the viewResolver can befound here.
  • mountNode :optional -HTMLDOMNode - supply a HTML DOM Node to mount the server rendered component in the case of partial/non-full page rendering.
  • history :optional -Object - supply any custom history object to be used by the react-router.

Data for component rendering

The actual data that gets fed into the component for rendering is therenderOptions object thatexpress generates.

If you don't want to pass all that data, you can pass in an array of object keys or dot-lookup paths that react-engine can filter out from therenderOptions object before passing it into the component for rendering.

// example of using `renderOptionsKeysToFilter` to filter `renderOptions` keysvarengine=ReactEngine.server.create({renderOptionsKeysToFilter:['mySensitiveData','somearrayAtIndex[3].deeply.nested'],routes:require(path.join(__dirname+'./reactRoutes'))});

Notes:

  • The stringsrenderOptionsKeysToFilter will be used withlodash.unset, so they can be either plain object keys for first-level properties ofrenderOptions, or dot-separated "lookup paths" as shown in thelodash.unset documentation. Use these lookup paths to filter out nested sub-properties.
  • By default, the following three keys are always filtered out fromrenderOptions no matter whetherrenderOptionsKeysToFilter is configured or not.
    • settings
    • enrouten
    • _locals

Handling redirects and route not found errors on the server side

While using react-router, it matches the url to a component based on the app's defined routes. react-engine captures the redirects and not-found cases that are encountered while trying to run the react-router'smatch function on the server side.

To handle the above during the lifecycle of a request, add an error type check in your express error middleware. The following are the three types of error that get thrown by react-engine:

Error TypeDescription
MATCH_REDIRECT**indicates that the url matched to a redirection
MATCH_NOT_FOUNDindicates that the url did not match to any component
MATCH_INTERNAL_ERRORindicates that react-router encountered an internal error

** for MATCH_REDIRECT error,redirectLocation property of the err has the new redirection location

// example express error middlewareapp.use(function(err,req,res,next){console.error(err);// http://expressjs.com/en/guide/error-handling.htmlif(res.headersSent){returnnext(err);}if(err._type&&err._type===ReactEngine.reactRouterServerErrors.MATCH_REDIRECT){returnres.redirect(302,err.redirectLocation);}elseif(err._type&&err._type===ReactEngine.reactRouterServerErrors.MATCH_NOT_FOUND){returnres.status(404).send('Route Not Found!');}else{// for ReactEngine.reactRouterServerErrors.MATCH_INTERNAL_ERROR or// any other error we just send the error message backreturnres.status(500).send(err.message);}});

Yeoman Generator

There is a Yeoman generator available to create a new express or KrakenJS application which uses react-engine:generator-react-engine.

Performance Profiling

Pass in a function to theperformanceCollector property to collect thestatsobject for every render.

stats

The object that contains the stats info for each render by react-engine.It has the below properties.

  • name - Name of the template or the url in case of react router rendering.
  • startTime - The start time of render.
  • endTime - The completion time of render.
  • duration - The duration taken to render (in milliseconds).
// examplefunctioncollector(stats){console.log(stats);}varengine=require('react-engine').server.create({routes:'./routes.jsx'performanceCollector:collector});

Notes

  • On the client side, the state is exposed in a script tag whose id isreact-engine-props
  • When Express'sview cache app property is false (mostly in non-production environments), views are automatically reloaded before render. So there is no need to restart the server for seeing the changes.
  • You can usejs as the engine if you decide not to write your react views injsx.
  • Blog on react-engine
  • You can addnonce in_locals, which will be added inscript tag that gets injected into the server rendered pages, likeres.locals.nonce = 'nonce value'

License

Apache Software License v2.0

About

a composite render engine for universal (isomorphic) express apps to render both plain react views and react-router views

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors31


[8]ページ先頭

©2009-2025 Movatter.jp