About Transfiler

고승우·2025년 6월 16일
0

React

목록 보기
1/1

Transfiler is quite unfamiliar to me. As a big fan of Rust, I never heard about the Transfiler (But it doesn't mean that I understand the compiler very wellㅠ). Let's look around the Transfiler.

What is Transfiler?

Transfiler converts from programming language(or version) to similar level of language. Different with Compiler, Transfiler converts high level language -> high level language

Role of the Tranfiler

  1. Support language compatability
    • e.g. Newest ESNext JS -> Old version of ES5 code
  2. Support extended syntax
    • e.g. JSX -> React.createElement
    • e.g. TypeScript -> Vanilla JS
  3. Code optimization & convert
    • e.g. optional chaining(?.) -> code with IF branches

Internal Working Flow

  1. Parser
    • Break down the input source code into a stream of tokens -> Generate AST(Abstract Syntax Tree)
    • Lexing (Tokenization)
      • Reads the raw source characters
      • Removes whitespace and comments
      • Splits into a stream of tokens
    • Parsing (Syntax Analysis)
      • Reads the token stream in order
      • Applies grammar rules to group tokens
      • Builds AST nodes and establishes parent–child relationships
  2. Transform
    • Transform node while Traversing AST
    • e.g. Convert JSXnode into CallExpression(React.createElement, ...) node
    • Enable various converting logic into plugin system like Babel plugin
    • Type checking and optimization logic also be performed at this stage
  3. Code genereation
    • Print Text code which is composed with converted AST
    • Also works with formatters like Prettier to insert spaces, line breaks, and semicolons
    • Generate Sourcemap: Includes code mapping information before and after transformation'

Example

1. Input source

function Title() {
  return <h1 className="title">Hello</h1>;
}

2. Parsing -> AST

  • JSXElement node found

3. Transform plugin(@babel/plugin-transform-react-jsx)

  • JSXElement ->
React.createElement(
  "h1",
  { className: "title" },
  "Hello"
);

4. Generate code

function Title() {
  return React.createElement("h1", { className: "title" }, "Hello");
}
profile
٩( ᐛ )و 

0개의 댓글