-
Notifications
You must be signed in to change notification settings - Fork 4
/
recast-demo.js
83 lines (67 loc) · 1.63 KB
/
recast-demo.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
const recast = require('recast');
const fs = require('fs');
const source = ` console.log('leading');
`
// const ast = recast.parse(fs.readFileSync('fixtures/arrow-function-inline-return/source/recast-oddities.js', 'utf8'));
// const ast = recast.parse(
// `
// console.log('leading');
// `
// );
// console.log(recast.print(ast).code);
const {parse: babelParse, transformSync: babelTransformSync} = require('@babel/core');
const _ = require('lodash');
function transform({source, filePath}) {
const defaultBabelOpts = {
filename: filePath,
sourceType: 'module',
presets: [],
plugins: [],
ast: true,
parserOpts: {
tokens: true
}
};
const parser = {
parse(sourceToParse, opts) {
const optsToPass = _.omit(
opts,
'jsx',
'loc',
'locations',
'range',
'comment',
'onComment',
'tolerant',
'ecmaVersion'
);
const babelOpts = {
...optsToPass,
...defaultBabelOpts
};
console.log({babelOpts});
return babelParse(sourceToParse, babelOpts);
}
};
console.log('attempting parse');
const ast = recast.parse(source, {parser});
console.log('Recast direct print:')
console.log(recast.print(ast));
const setAst = () => ({
visitor: {
Program(path) {
path.replaceWith(ast.program);
}
}
});
const babelResult = babelTransformSync('', {
...defaultBabelOpts,
plugins: [setAst]
});
console.log('After babel trivial transform:')
console.log(recast.print(babelResult.ast));
}
transform({
source,
filePath: 'demo.js'
});