forked from abramz/gulp-render-react
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
43 lines (38 loc) · 1.38 KB
/
index.js
File metadata and controls
43 lines (38 loc) · 1.38 KB
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
'use strict';
var gutil = require('gulp-util');
var through = require('through2');
var React = require('react');
var nodejsx = require('node-jsx');
function renderToString(filePath, props) {
var component = React.createFactory(require(filePath));
var element = component(props);
return new Buffer(React.renderToString(element));
}
function renderToStaticMarkup(filePath, props) {
var component = React.createFactory(require(filePath));
var element = component(props);
return new Buffer(React.renderToStaticMarkup(element));
}
module.exports = function (type, props) {
props = props || {};
if (type !== 'string' && type !== 'markup') {
throw new gutil.PluginError('gulp-react-render', '`type` required (`string` or `markup`)');
}
return through.obj(function (file, enc, cb) {
try {
// temporary before we allow src extension in options
nodejsx.install({ extension: '.jsx' });
if (type === 'string') {
file.contents = renderToString(file.path, props);
} else if (type === 'markup') {
file.contents = renderToStaticMarkup(file.path, props);
}
// temporary before we allow dest extension in options
file.path = gutil.replaceExtension(file.path, '.html');
this.push(file);
} catch (err) {
this.emit('error', new gutil.PluginError('gulp-react-render', err, {fileName: file.path }));
}
return cb();
});
};