egg-view-react-ssr
React server side render solution for egg
Install
$ npm i egg-view-react-ssr --save
Usage
// {app_root}/config/plugin.js
exports.reactssr = {
enable: true,
package: 'egg-view-react-ssr',
};
Version
1.x.x
egg-view-react-ssr depends on egg-view-react plugin
2.x.x
egg-view-react-ssr no longer depends on egg-view-react plugin, egg-view-react-ssr has an independent function that can run on its own
- 2.0.0-2.1.1: react and react-dom dependence in plugin dependence
-
2.2.0: react and react-dom are not inside in plugin dependence
Configuration
// {app_root}/config/config.default.js
exports.reactssr = {
// doctype: '<!doctype html>',
// layout: path.join(app.baseDir, 'app/view/layout.js'),
// manifest: path.join(app.baseDir, 'config/manifest.json'),
// injectHeadRegex: /(<\/head>)/i,
// injectBodyRegex: /(<\/body>)/i,
// injectCss: true,
// injectJs: true,
// crossorigin: false,
// injectRes: [],
// mergeLocals: true,
// fallbackToClient: true, // fallback to client rendering if server render failed
// afterRender: (html, context) => { /* eslint no-unused-vars:off */
// return html;
// },
};
see config/config.default.js for more detail.
Render
render
Server Render, Call when server render bundle error, will try client render**
// controller/home.js
exports.index = function* (ctx) {
yield ctx.render('index/index.js', { message: 'egg react server side render'});
};
renderClient
, Use React render layout
Client Render, Call when client render, render layout
exports.reactssr.layout
by React
// controller/home.js
exports.client = function* (ctx) {
yield ctx.renderClient('index/index.js',{ message: 'egg react client render'});
};
renderAsset
, Use render layout by viewEngine, default nunjucks
Asset Render, Call - when asset render, you can render layout
exports.reactssr.layout
by viewEngine, default useegg-view-nunjucks
- you must install the specified engine dependence, such as
egg-view-nunjucks
oregg-view-ejs
- The context provides an
asset
object that can getjs
,css
,state
information. layout template
use default viewEngine nunjucks
// controller/home.js
exports.asset = function* (ctx) {
yield ctx.renderAsset('index/index.js', { message: 'egg react asset render'});
};
scope render viewEngine config
// controller/home.js
exports.asset = function* (ctx) {
yield ctx.renderAsset('index/index.js', { message: 'egg react asset render'}, { viewEngine: 'ejs' });
};
Example
React server side render example, please see egg-react-webpack-boilerplate
Questions & Suggestions
Please open an issue here.