2017-01-31 31 views
0

我想在我的babel插件中做兩個替換。而第二次更換應該只在第一次完成後纔會發生。Babel插件(Visitor pattern) - 它是如何工作的

module.exports = function(babel) { 
    const t = babel.types; 
    return { 
     visitor: { 
      FunctionExpression: function(path) { 
       //Conversion to arrow functions 
       path.replaceWith(t.arrowFunctionExpression(path.node.params, path.node.body, false)); 
      }, 
      ThisExpression: function(path) { 
       //Converting all this expressions to identifiers so that it won't get translated differently 
       path.replaceWith(t.identifier("this")); 
      } 
     } 
    }; 
} 

在我的「FunctionExpression」的AST樹中,「ThisExpression」存在於樹的某處。我只希望第二次轉換完成後才能進行第一次轉換。我如何實現這一目標?

回答

0

我想通了。 瞭解如何編寫babel插件的最佳地點。 Here

module.exports = function(babel) { 
    const t = babel.types; 
    return { 
     visitor: { 
      FunctionExpression: { 
       enter: function(path) { 
        path.traverse(updateThisExpression); 
        //Conversion to arrow functions 
        let arrowFnNode = t.arrowFunctionExpression(path.node.params, 
         path.node.body, false); 
        path.replaceWith(arrowFnNode); 
       } 
      } 
     } 
    }; 
} 

const updateThisExpression = { 
    ThisExpression: { 
     enter: function(path) { 
      //Converting all this expressions to identifiers so that 
      //it won't get translated differently 
      path.replaceWith(t.identifier("this")); 
     } 
    } 
}; 

你寫,你用了 「FunctionExpression」 遊客..內穿越另一個訪問者對象;)

相關問題