-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathacorn.js
105 lines (90 loc) · 1.99 KB
/
acorn.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
const { parse } = require('acorn');
const { traverse, transformSync } = require('@babel/core');
const babelGenerator = require('@babel/generator').default;
const astTraverse = require("ast-traverse");
const { parse: babylonParse } = require('babylon');
const alter = require("alter");
const codeStr = `
let a = 123;
let b, c = 'abc';
function aa () {};
`;
/**
* acorn编译
* @type {Array}
*/
const ctx = [];
function diyTransform(node, result = '') {
const { type } = node;
switch (type) {
case 'VariableDeclaration':
const { kind, declarations } = node;
result = kind + ' ';
return `${kind} ${declarations.map(diyTransform).join()};`;
case 'VariableDeclarator':
const { id, init } = node;
return `${diyTransform(id)}${init ? ` = ${diyTransform(init)}` : ''}`;
case 'Identifier':
const { name } = node;
return name;
case 'Literal':
const { raw = '' } = node;
return raw;
}
};
const ast = parse(codeStr);
astTraverse(ast, {
pre(node) {
const { type, start, end } = node;
switch (type) {
case 'VariableDeclaration':
node.kind = 'var';
ctx.push({
start,
end,
str: diyTransform(node),
});
break;
default:
break;
}
},
});
// test
// console.log(alter(codeStr, ctx));
/***********************************/
/**
* babylon编译
* @type {[type]}
*/
const babylonAst = babylonParse(codeStr);
traverse(babylonAst, {});
//test
// console.log(babelGenerator(babylonAst, {
// minified: false,
// }).code);
/***********************************/
/**
* babel编译
* @type {[type]}
*/
const { ast: babelAst } = transformSync(codeStr, {
ast: true,
code: false,
sourceMap: true,
babelrc: false,
configFile: false,
presets: ['@babel/env'],
});
traverse(babelAst, {
VariableDeclarator(path) {
// ...
},
});
module.exports = () => {
return 'aaa';
};
// test
// console.log(babelGenerator(babelAst, {
// minified: false,
// }).code);