Created
July 6, 2019 08:16
-
-
Save stormslowly/8b0d1b2c230ebe7414afc9896db650b9 to your computer and use it in GitHub Desktop.
ast demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import generate from "@babel/generator"; | |
import {parse} from "@babel/parser"; | |
import traverse from "@babel/traverse"; | |
import {identifier, isIdentifier, isMemberExpression, memberExpression} from "@babel/types"; | |
import * as fs from 'fs' | |
const file = process.argv[2] | |
const ast = parse(fs.readFileSync(file, 'utf-8’)) // 解析得到 ast | |
traverse(ast, { | |
CallExpression(path) { // 当遍历到“调用表达式”时进入此回调 | |
if (isMemberExpression(path.node.callee) && // 被调用的函数来自一个成员表达 | |
isIdentifier(path.node.callee.property, {name: 'getPositionX'})) { // 成员属性是名为 getPositionX 的标识符 | |
path.replaceInline(memberExpression(path.node.callee.object, identifier('x'))) // 把调用表达式替换成函数表达式,对象为原本的对象,属性直接用 x | |
} | |
} | |
}) | |
console.log(generate(ast, {retainLines: true}).code); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment