vodkabears / babel-plugin-transform-react-ssr-try-catch

Wraps render() method in React.Component with try-catch statement

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Build Status

@doochik/babel-plugin-transform-react-ssr-try-catch

Babel plugin to wrap render() method in React.Component with try-catch statement.

Motivation

React 16 has error handling but for client rendering only.

This plugin performs simple transform which wraps event render() method with try-catch. Example:

// MyComponent.js

class MyCompoenent extends React.PureComponent {
  render() {
    return <div/>;
  }
}

This component will be transofmed to:

// MyComponent.js
const ReactSSRErrorHandler = require('./path/to/my/SSRErrorHandler.js');

class MyCompoenent extends React.PureComponent {
  render() {
      try {
          return this.__originalRenderMethod__();
      } catch (e) {
          return ReactSSRErrorHandler(e, this.constructor.name);
      }
  }

  __originalRenderMethod__() {
      return <div />;
  }
}

Actually, this is temporary solution until React doesn't support error handling in SSR.

Installation

npm install --save-dev @doochik/babel-plugin-transform-react-ssr-try-catch

Usage

You should enable this plugin only for server build. Use React 16 error boundaries from cient build.

.babelrc

{
    "plugins": [
        ["react-ssr-try-catch", {
            "errorHandler": "./path/to/my/SSRErrorHandler.js"
        }]
    ]
}

Options

errorHandler

Path to your errorHandler module. This is simple function with two arguments (error, componentName)

// SSRErrorHandler.js

module.exports = (error, componentName) => {
   // here you can log error and return fallback component or null.
}

About

Wraps render() method in React.Component with try-catch statement

License:MIT License


Languages

Language:JavaScript 100.0%