-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreact-declaration-loader.js
69 lines (63 loc) · 2.02 KB
/
react-declaration-loader.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
'use strict';
var esprima = require('esprima');
var traverse = require('./lib/traverse');
var astring = require('astring');
var contextVisitor = require('./lib/context-visitor');
var declarationVisitors = require('./lib/declaration-visitors');
var reactReferenceVisitor = require('./lib/react-reference-visitor');
module.exports = reactDeclarationLoader;
function reactDeclarationLoader(source) {
this.cacheable && this.cacheable();
var ast = esprima.parse(source, {
tokens: true,
range: true,
comment: true,
sourceType: 'module'
});
traverse(
ast,
contextVisitor,
declarationVisitors,
reactReferenceVisitor,
{
ProgramLeave: ProgramLeave
}
);
return source;
function ProgramLeave(program) {
var injectReact = false;
if (program._reactUnresolved) {
var declarations = program
._declarations.React || [];
var unresolvedInThisClosure = program._unresolvedInThisClosure;
if (unresolvedInThisClosure){
var conflicts = declarations
.filter(function(node){
return node._uniqueDeclaration;
}).length;
injectReact = !conflicts;
} else if (!declarations.length) {
injectReact = true;
}
}
if (injectReact) {
injectDeclaration();
}
function injectDeclaration() {
var injectIndex = 0;
var body = program.body;
while(injectIndex < body.length) {
var childNode = body[injectIndex];
if (!childNode.directive) {
break;
}
injectIndex = injectIndex + 1;
}
body.splice(injectIndex, 0, esprima.parse('var React = require(\'react\');'));
source = astring(ast, {
comment: true,
indent: ' '
});
}
}
}