Skip to content

Commit ec244f3

Browse files
committed
brwoserfy
1 parent c93d921 commit ec244f3

File tree

1 file changed

+26
-25
lines changed

1 file changed

+26
-25
lines changed

browserfy.js

+26-25
Original file line numberDiff line numberDiff line change
@@ -44,21 +44,31 @@ function createEnvify(env) {
4444
return visitProcessEnv
4545
}
4646

47-
function createGlobal(content) {
48-
var ast = esprima.parse(content, {
49-
range: true,
50-
tokens: true
51-
});
52-
var scopes = escope.analyze(ast).scopes;
53-
var gs = scopes.filter(function(scope) {
54-
return scope.type == 'global';
55-
})[0];
56-
47+
function createGlobal() {
5748
function visitGlobal(traverse, node, path, state) {
58-
var varGlobal = findVar(gs, node.name);
49+
var idx = 0;
50+
while (path[idx]) {
51+
if (path[idx].type === Syntax.FunctionExpression || path[idx].type === Syntax.Program ) {
52+
var scopes = escope.analyze(path[idx]).scopes.filter(function(item) {
53+
return item.block === path[idx];
54+
});
55+
var resolved = false;
56+
57+
scopes.every(function(scope) {
58+
if (findVar(scope, node.name)) {
59+
resolved = true;
60+
return false;
61+
}
62+
63+
return true;
64+
});
5965

60-
if (varGlobal) {
61-
return false;
66+
if (resolved) {
67+
return false;
68+
}
69+
}
70+
71+
idx++;
6272
}
6373

6474
utils.catchup(node.range[0], state)
@@ -77,23 +87,14 @@ function createGlobal(content) {
7787
function findVar(scope, name) {
7888
var refs = scope.variables;
7989
var i = 0;
80-
var ref, childScope;
90+
var ref;
8191

8292
while ((ref = refs[i++])) {
8393

8494
if (ref.name === name) {
8595
return ref;
8696
}
8797
}
88-
89-
i = 0;
90-
91-
while ((childScope = scope.childScopes[i++])) {
92-
93-
if ((ref = findVar(childScope, name))) {
94-
return ref;
95-
}
96-
}
9798
}
9899

99100
return visitGlobal;
@@ -103,9 +104,9 @@ function createGlobal(content) {
103104
module.exports = function(content) {
104105
var visitors = [createEnvify({
105106
NODE_ENV: 'production'
106-
}), createGlobal(content)];
107+
}), createGlobal()];
107108
return jstransform.transform(visitors, content).code
108109
}
109110

110-
// console.log(module.exports('var global2 = global.xxx; global.xxx = xxx;if (process.env.NODE_ENV === "production") {xx.global.xxx =1;}'));
111+
// console.log(module.exports('(function(){ var global2 = global.xxx; global.xxx = xxx;if (process.env.NODE_ENV === "production") {xx.global.xxx =1;} })();(function() {var global = 1; global.xxx = 1;})();'));
111112

0 commit comments

Comments
 (0)