This repository has been archived by the owner on Apr 4, 2022. It is now read-only.
forked from kingback/babel-plugin-transform-require-default
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
83 lines (78 loc) · 2.46 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
var requireDefaultFunc = '__require_default_func__';
var requireDefaultFuncTemp = `function ${requireDefaultFunc}(module) {
if (module && module.__esModule && typeof module["default"] !== "undefined") {
for (var k in module) {
if (k !== "default" && k !== "__esModule") {
module["default"][k] = module[k];
}
}
return module["default"];
}
return module;
}`;
function typeOf(v) {
return Object.prototype.toString.call(v).slice(8, -1).toLowerCase();
}
function isExcluded(exclude, module) {
if (exclude) {
switch (typeOf(exclude)) {
case 'string':
return exclude === module;
case 'regexp':
return exclude.test(module);
case 'function':
return exclude(module);
case 'array':
var excluded = false;
exclude.some(function(e) {
return (excluded = isExcluded(e, module));
});
return excluded;
default:
return false;
}
} else {
return false;
}
}
module.exports = function (babel, options) {
options = options || {};
var { types, template } = babel;
var requirePaths;
function isRequireCallExpression(path) {
const node = path.node;
const parentNode = path.parent;
return types.isIdentifier(node.callee, { name: 'require' }) && // ignore a.require('xxx')
types.isStringLiteral(node.arguments[0]) && // ignore require(), require(aaa), require(111)
node.arguments.length === 1 && // ignore require('xxx', a)
node.arguments[0].value && // ignore require('')
!(types.isMemberExpression(parentNode) && (parentNode.property.name || parentNode.property.value) === 'default'); // ignore require('xxx').default and require('xxx')['default']
}
return {
visitor: {
Program: {
enter() {
requirePaths = [];
},
exit(path) {
if (!requirePaths.length) return;
path.node.body.unshift(template(requireDefaultFuncTemp)());
requirePaths.forEach(function(p) {
if (typeof p.node.arguments[0].value !== 'undefined') {
p.replaceWithSourceString(`${requireDefaultFunc}(require("${p.node.arguments[0].value}"))`);
}
});
}
},
CallExpression(path) {
if (
isRequireCallExpression(path) &&
requirePaths.indexOf(path) < 0 &&
!isExcluded(options.exclude, path.node.arguments[0].value)
) {
requirePaths.push(path);
}
}
}
};
}