-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
57 lines (50 loc) · 1.38 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
const parser = require('@babel/parser')
const traverse = require('@babel/traverse').default
module.exports = function (
src,
{
dynamicImport = true,
parse = {
sourceType: 'module',
plugins: ['jsx', 'typescript', 'dynamicImport'],
},
} = {}
) {
const modules = { strings: [], expressions: [] }
let ast
if (typeof src === 'string') {
const moduleRe = /\b(require|import|export)\b/
if (!moduleRe.test(src)) {
return modules
}
ast = parser.parse(src, parse)
} else {
ast = src
}
traverse(ast, {
enter(path) {
if (path.node.type === 'CallExpression') {
const callee = path.get('callee')
const isDynamicImport = dynamicImport && callee.isImport()
if (callee.isIdentifier({ name: 'require' }) || isDynamicImport) {
const arg = path.node.arguments[0]
if (arg.type === 'StringLiteral') {
modules.strings.push(arg.value)
} else {
modules.expressions.push(src.slice(arg.start, arg.end))
}
}
} else if (
path.node.type === 'ImportDeclaration' ||
path.node.type === 'ExportNamedDeclaration' ||
path.node.type === 'ExportAllDeclaration'
) {
const { source } = path.node
if (source && source.value) {
modules.strings.push(source.value)
}
}
},
})
return modules
}