-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
88 lines (65 loc) · 2.17 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
'use strict';
var gutil = require('gulp-util');
var through = require('through2');
var htmlTags = require('html-tags');
function pseudoGuessTags(html) {
var tagsRe = /<\s*(\w+)/g;
var match = tagsRe.exec(html);
var results = {};
var tag;
while (match !== null) {
if (match) {
tag = match[1];
if ( htmlTags.indexOf( tag ) !== -1 ) {
tag = 'React';
}
results[tag] = true;
}
match = tagsRe.exec(html);
}
return Object.keys(results);
}
module.exports = function(options) {
options = options || {};
options.requires = options.requires || [];
options.requires.React = options.requires.React || 'react';
return through.obj(function(file, enc, cb) {
if (file.isNull()) {
this.push(file);
return cb();
}
if (file.isStream()) {
this.emit('error', new gutil.PluginError('gulp-jsxify', 'Streaming not supported'));
return cb();
}
var str = file.contents.toString();
var usedTags = pseudoGuessTags(str);
var requiresTagNames = Object.keys(options.requires);
var requires = requiresTagNames
.filter (function(tag){
return usedTags.indexOf(tag) > -1;
})
.map(function(reqName) {
var reqPath = options.requires[reqName];
return 'var ' + reqName + ' = require(\'' + reqPath + '\');';
})
.join('\n');
usedTags.forEach(function(tag){
if (requiresTagNames.indexOf( tag ) === -1 ) {
gutil.log('WARNING: unknown tag ' + tag);
}
});
var jsxContent = '/** @jsx React.DOM */\n' +
'\'use strict\';\n' +
requires + '\n' +
'module.exports = function(args){ \n' +
' return (\n' +
str +
' );\n' +
'};';
file.contents = new Buffer(jsxContent);
file.path = gutil.replaceExtension(file.path, '.jsx');
this.push(file);
cb();
});
};