日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Babylon-AST初探-代码更新删除(Update Remove)

發布時間:2025/3/8 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Babylon-AST初探-代码更新删除(Update Remove) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

??通過前兩篇文章的介紹,大家已經了解了Create和Retrieve,我們接著介紹Update和 Remove操作。Update操作通常配合Create來完成。我們這篇文章主要介紹幾個常用的NodePath`API:replace、insert、remove`。具體也可以看babel-handbook中的Manipulation章節。

replaceWith 使用新的節點進行替換

將加法運算替換成乘法

const code = `const c = a + b` const ast = babylon.parse(code)traverse(ast, {BinaryExpression(path) {// 注意這里要有判斷,否則會無限進入`BinaryExpression`// https://stackoverflow.com/questions/37539432/babel-maximum-call-stack-size-exceeded-while-using-path-replacewithif (path.node.operator === '+') {path.replaceWith(t.binaryExpression('*', path.node.left, path.node.right))}} })console.log(generate(ast, {}, code).code) // const c = a * b;

將this.count替換為this.data.count

??轉換前后的AST展示如下圖:

??我們需要做的是,找到符合this.count的ThisExpression,然后把它替換為this.data

const code = `this.count` const ast = babylon.parse(code)traverse(ast, {MemberExpression(path) {if (t.isThisExpression(path.node.object) &&t.isIdentifier(path.node.property, {name: 'count'})) {path.get('object') // 獲取`ThisExpresssion`.replaceWith(t.memberExpression(t.thisExpression(), t.identifier('data')))}} }) console.log(generate(ast, {}, code).code) // this.data.count;

replaceWithSourceString 直接使用代碼替換

??上個例子中將this.count替換為this.data.count的部分,通過t.memberExpression可以構造node。更簡單的操作可以直接使用replaceWithSourceString,個人覺得這個API很好用。

path.get('object').replaceWithSourceString('this.data')

插入操作

??插入是樹操作的一種常見操作。子節點是個Array,前、中、后各種位置都可以插入新節點。下面來介紹下pushContainer、unshiftContainer、insertBefore、insertAfter操作。

??這里以給obj對象新增一個屬性myprop: 'hello my property'為例:

const code = ` const obj = {count: 0,message: 'hello world' } ` const ast = babylon.parse(code)const property = t.objectProperty(t.identifier('myprop'),t.stringLiteral('hello my property') )

pushContainer 父節點的操作

??父節點為子節點Array插入一個node

traverse(ast, {ObjectExpression(path) {path.pushContainer('properties', property)} })

insertAfter 兄弟節點的操作

??insertAfter也可以完成上述操作,需要找到message屬性,然后在后面插入node就搞定啦

traverse(ast, {ObjectProperty(path) {if (t.isIdentifier(path.node.key, {name: 'message'})) {path.insertAfter(property)}} })

??unshiftContainer和insertBefore與上面兩個相對應,這里不再舉例了,大家可以自己試一試。

??因為properties是個數組,因此,我們可以直接使用數組操作

traverse(ast, {ObjectExpression(path) {// path.pushContainer('properties', property)path.node.properties.push(property)} })

Remove 自我毀滅

??Remove方法極為簡單,找到要刪除的NodePath,執行Remove就結束了。如上述代碼,我們要刪除message屬性,代碼如下:

traverse(ast, {ObjectProperty(path) {if (t.isIdentifier(path.node.key, {name: 'message'})) {path.remove()}} })

到目前為止,AST的CURD我們都介紹完了,下面一篇文章以vue轉小程序為例,我們來實戰一波。

總結

以上是生活随笔為你收集整理的Babylon-AST初探-代码更新删除(Update Remove)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。