如何通过babel去操作ast, 并生成对应的代码。
修改对象名,比如Taro.xxx 修改为wx.xxx
const babel = require('@babel/core')
let traverse = require('@babel/traverse').default
const generate = require('@babel/generator').default
const types = require('@babel/types');
const code = 'wx.login();let env = wx.env'
const { ast } = babel.transformSync(code, { ast: true })
traverse(ast, {
BlockStatement(path) {
path.scope.rename('wx', 'ft')
},
Identifier(path) {
if (path.isReferenced() && path.node.name === 'wx') {
path.replaceWith(types.identifier('ft'))
}
},
})
console.log(generate(ast, {}).code)
在代码中插入对应的节点,比如在某个对象中插入一个属性
const babel = require('@babel/core');
let traverse = require('@babel/traverse').default
const generate = require('@babel/generator').default
const types = require('@babel/types');
const code = 'let a = { b: 2, c: 1 }'
const { ast } = babel.transformSync(code, { ast: true })
traverse(ast, {
ObjectExpression(path) {
path.node.properties.push(
types.objectProperty(
types.identifier("d"),
types.identifier("2")
)
)
}
})
console.log(generate(ast, {}).code)
找到代码中的依赖文件
const babel = require('@babel/core');
let traverse = require('@babel/traverse').default
const code = 'const demo = require("./demo"); import test from "test.js" '
const { ast } = babel.transformSync(code, { ast: true })
traverse(ast, {
ImportDeclaration(path) {
console.log(path.node.source.extra.rawValue)
},
CallExpression(path) {
if (path.node.callee.name === 'require' && path.node.arguments) {
console.log(path.node.arguments[0].value)
}
}
})
在表达式前后插入一个方法
const babel = require('@babel/core');
let traverse = require('@babel/traverse').default
const types = require('@babel/types');
const generate = require('@babel/generator').default;
const code = 'var a = 1'
const { ast } = babel.transformSync(code, { ast: true })
traverse(ast, {
enter(path) {
if (types.isExpressionStatement(path.node)) {
try {
if (path.node.expression.callee.name === 'demo') {
return
}
} catch (error) {
}
}
const item = types.expressionStatement(
types.callExpression(
types.identifier('demo'),
[
types.identifier(`data`),
]
)
)
if (types.isStatement(path.node)) {
path.insertBefore(item)
path.insertAfter(item)
}
}
})
console.log(generate(ast, {}).code)
参考文档:https://juejin.cn/post/7045496002614132766
如果你喜欢我的作品,请考虑赞助我,以保持它们的可持续性。