forked from magalhas/express-react-engine
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
61 lines (50 loc) · 1.74 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
'use strict';
var React = require('react');
var defaults = require('lodash.defaults');
var path = require('path');
module.exports = function engineFactory (engineOptions) {
engineOptions = defaults(engineOptions || {}, {
extension: '.jsx',
babel: {},
docType: '<!DOCTYPE html>',
staticMarkup: false
});
if (engineOptions.babel) {
require('babel/register')(engineOptions.babel);
}
return function renderComponent (filename, options, callback) {
options = options || {};
try {
var markup = engineOptions.docType;
var Component = require(filename);
var instance = React.createElement(Component, options);
var componentMarkup;
if (engineOptions.staticMarkup) {
componentMarkup = React.renderToStaticMarkup(instance);
} else {
componentMarkup = React.renderToString(instance);
}
if (engineOptions.wrapper) {
var Wrapper = require(path.join(this.root, engineOptions.wrapper));
var wrapperInstance = React.createElement(Wrapper, {
body: componentMarkup,
props: options
});
markup += React.renderToStaticMarkup(wrapperInstance);
} else {
markup += componentMarkup;
}
if (options.settings.env === 'development') {
Object.keys(require.cache).forEach(function(module) {
if (new RegExp('\\' + engineOptions.extension + '$')
.test(require.cache[module].filename)) {
delete require.cache[module];
}
});
}
callback(null, markup);
} catch (error) {
callback(error);
}
};
};