forked from gpittarelli/jsstrings
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
54 lines (49 loc) · 1.2 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
const babylon = require('@babel/parser');
const traverse = require('@babel/traverse').default;
const t = require('@babel/types');
function parseVisitor(code, visitor, onComplete) {
// accept either pre-parsed ast or string of code
if (typeof code === 'string') {
code = babylon.parse(code, {
sourceType: 'module',
plugins: [
'asyncGenerators',
'classConstructorCall',
'classProperties',
'decorators-legacy',
'doExpressions',
'exportDefaultFrom',
'exportExtensions',
'nullishCoalescingOperator',
'flow',
'functionSent',
'functionBind',
'jsx',
'objectRestSpread',
'optionalChaining',
'dynamicImport'
]
});
}
traverse(code, {
enter: function(path) {
const node = path.node;
if (path.isStringLiteral() || path.isDirectiveLiteral()) {
visitor(node.value);
} else if (path.isTemplateLiteral()) {
for (const q of node.quasis) {
visitor(q.value.raw);
}
}
}
});
}
function parse(code) {
const out = [];
parseVisitor(code, str => out.push(str));
return out;
}
module.exports = {
parse,
parseVisitor
};