npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

anemone-machina

v0.0.1

Published

a composite render engine for express apps to render both plain react views and react-router views

Downloads

54

Readme

anemone-machina

Build Status

What is anemone-machina?

  • a react render engine for Universal (previously Isomorphic) JavaScript apps written with express
  • renders both plain react views and optionally react-router views
  • enables server rendered views to be client mountable

Install

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

Usage On Server Side

Setup in an Express app
var Express = require('express');
var ReactEngine = require('anemone-machina');

var app = Express();

// create an engine instance
var engine = ReactEngine.server.create({
  /*
    see the complete server options spec here:
    https://github.com/paypal/anemone-machina#server-options-spec
  */
});

// set the engine
app.engine('.jsx', engine);

// set the view directory
app.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 view
app.set('view', require('anemone-machina/lib/expressView'));
Setup in a KrakenJS app's config.json
{
  "express": {
    "view engine": "jsx",
    "view": "require:anemone-machina/lib/expressView",
  },
  "view engines": {
    "jsx": {
      "module": "anemone-machina/lib/server",
      "renderer": {
        "method": "create",
        "arguments": [{
          /*
            see the complete server options spec here:
            https://github.com/paypal/anemone-machina#server-options-spec
          */
        }]
      }
    }
  }
}
Server options spec

Pass in a JavaScript object as options to the anemone-machina's server engine create method. The options object should contain the mandatory routes property with the route definition.

Additionally, it can contain the following optional 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. anemone-machina uses this behind the scenes to reload the routes file in cases where express's app property view 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 collects perf 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 to body the script is placed before the </body> tag. The only other value is head which appends the script before the </head> tag.
Rendering views on server side
var data = {}; // your data model

// for a simple react view rendering
res.render(viewName, data);

// for react-router rendering
// pass in the `url` and anemone-machina
// will run the react-router behind the scenes.
res.render(req.url, data);

Usage On Client Side (Mounting)

// assuming we use `browserify`
var client = require('anemone-machina').client;

// finally, boot whenever your app is ready
// example:
document.addEventListener('DOMContentLoaded', function onLoad() {

  // `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 */, function onBoot(data, history) {

  });
};

// if the data is needed before booting on
// client, call `data` function anytime to get it.
// example:
var data = client.data();
Client options spec

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

  • routes : required - Object - the route definition file.
  • viewResolver : required - Function - a function that anemone-machina needs to resolve the view file. an example of the viewResolver can be found 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 the renderOptions object that express generates.

If you don't want to pass all that data, you can pass in an array of object keys that anemone-machina can filter out from the renderOptions object before passing it into the component for rendering.

// example of using `renderOptionsKeysToFilter` to filter `renderOptions` keys
var engine = ReactEngine.server.create({
  renderOptionsKeysToFilter: ['mySensitiveDataThatIsIn_res.locals'],
  routes: require(path.join(__dirname + './reactRoutes'))
});

Note: By default, the following three keys are always filtered out from renderOptions no matter whether renderOptionsKeysToFilter 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. anemone-machina captures the redirects and not-found cases that are encountered while trying to run the react-router's match 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 anemone-machina:

Error Type | Description
-------------------- | -------------------------------------------------------- MATCH_REDIRECT** | indicates that the url matched to a redirection MATCH_NOT_FOUND | indicates that the url did not match to any component
MATCH_INTERNAL_ERROR | indicates that react-router encountered an internal error

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

// example express error middleware
app.use(function(err, req, res, next) {
  console.error(err);

  // http://expressjs.com/en/guide/error-handling.html
  if (res.headersSent) {
    return next(err);
  }

  if (err._type && err._type === ReactEngine.reactRouterServerErrors.MATCH_REDIRECT) {
    return res.redirect(302, err.redirectLocation);
  }
  else if (err._type && err._type === ReactEngine.reactRouterServerErrors.MATCH_NOT_FOUND) {
    return res.status(404).send('Route Not Found!');
  }
  else {
    // for ReactEngine.reactRouterServerErrors.MATCH_INTERNAL_ERROR or
    // any other error we just send the error message back
    return res.status(500).send(err.message);
  }
});

Performance Profiling

Pass in a function to the performanceCollector property to collect the stats object for every render.

stats

The object that contains the stats info for each render by anemone-machina. 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).
// example
function collector(stats) {
  console.log(stats);
}

var engine = require('anemone-machina').server.create({
  routes: './routes.jsx'
  performanceCollector: collector
});

Notes

  • On the client side, the state is exposed on the window object's property __REACT_ENGINE__
  • When Express's view 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 use js as the engine if you decide not to write your react views in jsx.

License

Apache Software License v2.0