You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
consttemplate=require('@babel/template').default;constgenerate=require("@babel/generator").default;constast=template.ast(`// JSvar a = 'abcd'`);ast.kind='let';ast.declarations[0].init.value=1234;console.log(ast.declarations[0].init);console.log(generate(ast).code);
ReturnStatement(path){path.replaceWithMultiple([t.expressionStatement(t.stringLiteral("Is this the real life?")),t.expressionStatement(t.stringLiteral("Is this just fantasy?")),t.expressionStatement(t.stringLiteral("(Enjoy singing the rest of the song in your head)")),]);}
还可以替换代码,不过经过测试,它有局限性,官方文档也不建议使用
FunctionDeclaration(path){path.replaceWithSourceString(`function add(a, b) { return a + b; }`);}
调试网站
AST测试网站
babel插件手册
babel
这段代码通过AST把
var a = 'abcd'
转化为let b = 1234
babel-plugins
babel
插件开发,plugin
字段配合visitor
筛选代码实现转化,转换的时候,是插件开始起作用的时候,babel给我们提供了一个visitor
的规范,让我们进入到这个流程中,我们可以通过visitor
来定义我们的访问逻辑visitor
支持很多类型,比如VariableDeclaration
,FunctionDeclaration
,ImportDeclaration
等,具体可以从AST测试网站展开分析访问者模式
可以在方法名用|来匹配多种不同的
type
,使用相同的处理函数遍历
可以手动查找就不要遍历
获取子节点的
path
获取父节点的
path
findParent
获取对应的子节点的
babel-types
配合
babel-types
工具进行代码替换增加等用多节点替换单节点
还可以替换代码,不过经过测试,它有局限性,官方文档也不建议使用
技巧
利用
visitor
访问者模式获取函数片段,然后通过path.get(类型)
一层一层定位到对应的子路径然后执行path.xxx
改造代码片段,获取子属性可以先在AST测试网站先查找结果loader里面获取文件的路径:
踩过的坑
类里面的方法要使用 ClassMethod 匹配,不能使用 FunctionExpression 匹配。
参考网站
The text was updated successfully, but these errors were encountered: