पाठ 6 / 30

Abstract Syntax Trees (AST)

समझें कि कैसे Babel और SWC कोड को पेड़ों में पार्स करते हैं और उन्हें रूपांतरित करते हैं।

कोड से AST तक

Transpilers सोर्स कोड को Abstract Syntax Tree में पार्स करते हैं — एक structured representation जहाँ हर कोड element एक node है। Transpiler फिर पेड़ को transform करता है और नया कोड generate करता है।

एक सरल transformation उदाहरण

Arrow function () => x एक regular function बन जाता है। AST node का प्रकार बदलता है, लेकिन अर्थ वही रहता है।

// Input (ES6)
const fn = () => 42;

// Output (ES5)
var fn = function() {
  return 42;
};
// The AST for `=>` was transformed to a function node

Plugins AST पर काम करते हैं

Babel और SWC plugins टेक्स्ट को फिर से नहीं लिखते। वे AST tree को traverse और modify करते हैं, फिर नए tree से कोड regenerate करते हैं। यह है कि plugins कैसे शक्तिशाली और precise हैं।

AST shapes और visitor patterns

Babel plugins visitor patterns का उपयोग करते हैं: AST को walk करें, node types को match करें, transformations को apply करें। AST structure को समझना custom Babel plugins लिखने के लिए key है।